Rails 3:如何返回 JSON 文档? [英] Rails 3: How To Return A JSON Document?
问题描述
我正在为我的应用程序创建一个简单的 API.我已经创建了控制器并完成了所有处理.但是,视图正在返回.
I'm in the process of creating a simple API for my application. I have create the controllers and did all the processing. However, the view is being returned.
如何将 JSON 文档而不是视图返回给用户?
How can I return a JSON document to the user instead of the view?
另外,如果出现错误,我还应该返回一个 JSON 文档还是...?
Also, if there's an error, should I also return a JSON document or... ?
谢谢!
推荐答案
将此添加到您的控制器
respond_to :html, :json
(如果您只需要 json-api,请删除 html).
(remove html if you only want json-api).
在您的操作中,您可以简单地使用 respond_with 调用,例如:
In your actions you can then simply use a respond_with call, like:
respond_with(@posts = Post.all)
如果格式为 JSON,它将呈现 JSON 对象,如果请求 html,它将呈现您的 html-view.如果您的路由是作为标准资源创建的,只需在 url 中添加 .json 后缀就会为您提供 JSON 结果,即.如果路由被指定为:
It will render JSON-object if format is JSON, and it will render your html-view if html is requested. If your routes are created as standard resources, simply adding .json suffix to the url will give you the JSON-result, ie. if the route is specified as:
resources :posts
这篇关于Rails 3:如何返回 JSON 文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!