Reputation: 1945
Until now, my team has used HTTP requests to create and modify a specific ActiveRecord object in our project. The related controller methods only render as json:
render json: { json: 'goes here' }
I'm creating a basic CRUD interface to do this, which should render an HTML page (render :html
) however, we also have a secondary API that relies on being able to call these controller actions through HTTP requests and get a json response back.
I've tried using a respond_to
block as follows to achieve this:
respond_to do | format |
format.json { render json: { json: 'goes here' } }
format.html # Appropriate view
end
However, even with direct HTTP requests (tested using cURL in a terminal), I always get an HTML response back. I've tried using a constraint
in the routes file, but not even that can get a JSON response to come out.
Is there something more I need to do, either on the server or client side, in order to get a JSON response from HTTP requests, while still rendering the appropriate view when the request comes from a form? Thank you!
Upvotes: 2
Views: 329
Reputation: 336
If you want to execute a particular format, e.g json, so you need to pass that in the params from where the request is coming, with the key value: format
whatever_path(format: :json)
Upvotes: 1
Reputation: 27961
If you look in the output from rake routes
then you'll see all your URIs have this (.format)
suffix to them. The parens mean that it's optional. If not provided (and if the Accept
header(s) don't disambiguate the request) then Rails defaults to responding with HTML.
So in your cURL command just provide the .json
format and Rails will respond with the right thing:
curl localhost:3000/foos.json
Upvotes: 3