Fendo
Fendo

Reputation: 339

How do I make a json request to a rails 3 website?

I know that if I have a url like

mysite/posts/1

The default type returned to me is html. I can get an xml version of the resource by just doing

mysite/posts/1.xml

But how do I get a json version? Is the following supposed to work?

mysite/posts/1.json

Reason I ask is because it doesn't seem to be working. So I figured I should find out if it's "supposed" to work this way before investigating further.

Upvotes: 1

Views: 727

Answers (1)

Mike Yockey
Mike Yockey

Reputation: 4593

You're doing it right, but if the Controller isn't setup to respond to json requests you won't get anything. You'll have a respond_to block like this:

respond_to do |format|
  format.html
  format.xml { render :xml => @model_var.to_xml }
  format.json { render :json => @model_var.to_json } #without this line, .json requests will go unanswered by the web server.
end

Upvotes: 4

Related Questions