![](/img/trans.png)
[英]Ruby on rails: What's the difference between respond_to and respond_with?
[英]Setting up custom formats for respond_to and respond_with in Ruby on Rails 4
当我尝试使用respond_to /来表示自定义输出时,我得到一个ActionView :: MissingTemplate ,就像它表现出xml / json输出一样。
我的对象上有自定义输出格式。
@item.to_custom
我已经在mime_types.rb中注册了自定义Mime :: Type的格式。
Mime::Type.register "application/custom", :custom
我把它列在我的控制器的respond_to选项中
class ItemsController < ApplicationController
respond_to :html, :xml, :custom
然后我在show show结束前有一个respond_with方法。
def show
@item = Item.find(params[:id])
respond_with(@item)
end
当我访问items / 1234.xml时,我得到了xml输出。 当我尝试访问items / 1234.custom时,我得到一个错误ActionView :: MissingTemplate 。 我可以通过添加文件app / views / show.custom.ruby来修复它:
@item.to_custom
有没有办法让to_custom在response_to / with setup中像to_xml或to_json一样工作? 只需使用to_custom方法而不需要模板? 或者我是否必须使用明确调用该方法的视图模板?
如果要在不显式添加视图模板的情况下进行渲染,则需要手动为自定义格式添加Renderer
。
Rails内置格式xml
和json
具有从Rails框架中自动添加的渲染器,这就是为什么它们开箱即用而你的自定义格式没有( 源代码 )。
尝试在初始化程序中或在您注册MIME类型的下方添加此项
# config/initializers/renderers.rb
ActionController::Renderers.add :foo do |object, options|
self.content_type ||= Mime::FOO
object.respond_to?(:to_foo) ? object.to_foo : object
end
注意:不要使用custom
作为格式名称,因为它将与respond_with
内部中的方法冲突。
有一篇很棒的博客文章解释了如何深入构建自定义Renderers
: http : //beerlington.com/blog/2011/07/25/building-a-csv-renderer-in-rails-3/
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.