Reputation: 1011
I want to test the JSON response from a Rails controller GET action using only a browser.
If the url to the resource is http://localhost:3000/models/action
, how do I tell rails to return the response as JSON?
Upvotes: 1
Views: 834
Reputation: 1451
You have to define in the controller the respond format:
def action
@objects = Model.all
respond_to do |format|
format.html
format.json
end
end
OR as a shorcut
def action
@objects = Model.all
respond_to :html, :json
end
OR handle the format at controller level
class ModelsController < ApplicationController
respond_to :html, :json
def action
@objects = Model.all
respond_with(@objects)
end
end
And now when you are calling http://localhost:3000/models/action.json
the response will be JSON format
Upvotes: 0
Reputation: 1011
This is pretty simple once you figure out how to do it.
You can specify the type of the response by adding the type as an extension to the action.
For example, if we want the json response, could alter the request to be http://localhost:3000/models/action.json
.
Upvotes: 1