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
精彩评论