开发者

Rails 3: How To Return A JSON Document?

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.

How can I return a JSON document to the user instead of the view?

Also, if there's an error, sho开发者_如何学Pythonuld I also return a JSON document or... ?

Thanks!


Add this to your controller

   respond_to :html, :json

(remove html if you only want json-api).

In your actions you can then simply use a respond_with call, like:

   respond_with(@posts = Post.all)

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜