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

空扰寡人 提交于 2019-12-03 02:22:16
nathanvda

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.

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

dreeves

The following works for me. I believe you have to specify the "render" part for html explicitly or it will use the format.any.

respond_to do |format|
  format.html { render :html => @switches }
  format.json { render :json => @switches }
  format.xml  { render :xml  => @switches }
  format.all  { render :text => "we only have html, json, and xml" }
end
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!