编码
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 格式。”
我能找到的唯一 Rails 文档是
http://api.rubyonrails.org/classes/ActionController/MimeResponds/ClassMethods.html#method-i-respond_to
目前仅声明:
respond_to :html, :xml, :json
但是他们需要单独的 json 和 xml 模板,并且无法处理“目前仅支持 HTML 和 JSON 格式”的情况。
请您参考如下方法:
在 rails3 你会写:
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
文件顶部的块,详细说明预期的格式。例如。
respond_to :xml, :json, :html
即使在这种情况下,如果有人问
js
格式,
any
块被触发。
您还可以使用
respond_to
单独,如下:
@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
希望这可以帮助。