darksky
darksky

Reputation: 21019

Rails HTML Request Render JSON

In my controller, I'm supporting HTML and JSON in my index method by doing:

respond_to do |format|
  format.html
  format.json { render json: @user }
end

When pulling it up in the browser, it renders in HTML naturally. However, when I do a curl call with content-type being application/json to the /user resource (since it's the index method), I still get the HTML as a response.

How can I get the JSON as a response? What else do I need to specify?

Upvotes: 5

Views: 4719

Answers (1)

Baldrick
Baldrick

Reputation: 24340

You should append .json to the requested url, provided format is defined in the path in routes.rb. This is default when using resources. For example, rake routes should give you something like:

show_user GET    /users/:id(.:format) users#show

To get user in HTML

curl  http://localhost:3000/users/1  

To get user in JSON:

curl http://localhost:3000/users/1.json    

Upvotes: 8

Related Questions