在Rails 3中,response_to和format.all的工作原理与Rails 2不同吗? [英] In Rails 3, respond_to and format.all works differently than Rails 2?
问题描述
代码
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
以上内容将在Rails 2.2.2中运行.但是在Rails 3中,在浏览器上获取controller/index.html或index都将落在最后一行:目前仅支持HTML和JSON格式."
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."
我唯一可以找到的Rails文档是
The only Rails doc I can find on this is
当前仅指出:
respond_to :html, :xml, :json
但是它们需要用于json和xml的单独模板,并且无法处理目前仅支持HTML和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.
推荐答案
在rails3中,您应该编写:
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
但这仅与文件顶部的respond_to
块相对应,详细说明了预期的格式.例如
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
即使在这种情况下,例如,如果有人要求使用js
格式,也会触发any
块.
Even in that case, if anybody for instance asks the js
format, the any
block is triggered.
您还可以单独使用respond_to
,如下所示:
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
希望这会有所帮助.
这篇关于在Rails 3中,response_to和format.all的工作原理与Rails 2不同吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!