在Ruby on Rails 4中为respond_to和respond_with设置自定义格式

时间:2014-02-26 19:58:06

标签: ruby-on-rails ruby

我在尝试使用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

然后我在演出结束前有一个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方法而不需要模板?或者我是否必须使用明确调用该方法的视图模板?

1 个答案:

答案 0 :(得分:3)

如果您希望在不显式添加视图模板的情况下进行渲染,则需要为自定义格式手动添加Renderer

Rails内置格式xmljson具有从Rails框架内自动添加的渲染器,这就是为什么它们开箱即用而您的自定义格式不起作用的原因({{3 }})。

尝试在初始化程序中添加此项,或者在注册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内部的方法冲突。

有一篇优秀的博客文章解释了如何深入构建自定义Rendererssource code