Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Rails 3, respond_to and format.all works differently than Rails 2?

Tags:

the code

respond_to do |format|   format.html   format.json { render :json => @switches }   format.xml { render :xml => @switches.to_xml }   format.all { render :text => "only HTML, XML, and JSON format are supported at the moment." } end 

the above will work in Rails 2.2.2. But in Rails 3, getting controller/index.html or index on the browser will both fall into the last line: "only HTML and JSON format are supported at the moment."

The only Rails doc I can find on this is

http://api.rubyonrails.org/classes/ActionController/MimeResponds/ClassMethods.html#method-i-respond_to

which current only states:

respond_to :html, :xml, :json 

but they need separate templates for json and xml, and can't handle the "only HTML and JSON format are supported at the moment" case.

like image 725
nonopolarity Avatar asked Sep 08 '10 21:09

nonopolarity


People also ask

What does respond_ to do?

A respond_to shortcut it works the same way as writing the full respond_to block in index . It's a short way to tell Rails about all the formats your action knows about. And if different actions support different formats, this is a good way to handle those differences without much code.

What is Respond_to in Ruby?

respond_to is a Rails method for responding to particular request types. For example: def index @people = Person.find(:all) respond_to do |format| format.html format.xml { render :xml => @people.to_xml } end end.


2 Answers

In rails3 you would write:

respond_with(@switches) do |format|   format.html   format.json { render :json => @switches }   format.xml  { render :xml  => @switches }   format.all  { render :text => "only HTML, XML, and JSON format are supported at the moment." } end 

But this only works in correspondence with a respond_to block at the top of the file, detailing the expected formats. E.g.

respond_to :xml, :json, :html 

Even in that case, if anybody for instance asks the js format, the any block is triggered.

You could also still use the respond_to alone, as follows:

@switches = ... respond_to do |format|   format.html {render :text => 'This is html'}   format.xml  {render :xml  => @switches}   format.json {render :json => @switches}   format.all  {render :text => "Only HTML, JSON and XML are currently supported"} end 

Hope this helps.

like image 133
nathanvda Avatar answered Sep 28 '22 03:09

nathanvda


You may find it useful to watch this episode of railscasts, which illustrates the changes to controllers in Rails 3 and in particular the changes to the responder class (putting respond_to in the controller class itself and only using respond_with @object in the action):

http://railscasts.com/episodes/224-controllers-in-rails-3

like image 23
svilenv Avatar answered Sep 28 '22 03:09

svilenv