【问题标题】:Setting up custom formats for respond_to and respond_with in Ruby on Rails 4在 Ruby on Rails 4 中为 respond_to 和 respond_with 设置自定义格式
【发布时间】:2014-02-26 19:58:05
【问题描述】:

当我尝试让自定义输出与 respond_to/with 一起表现时,我得到一个 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 设置中像 to_xml 或 to_json 一样工作?只使用 to_custom 方法而不需要模板?还是我必须使用显式调用该方法的视图模板?

【问题讨论】:

    标签: ruby-on-rails ruby


    【解决方案1】:

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

    Rails 内置格式xmljson 具有从Rails 框架内自动添加的渲染器,这就是为什么它们可以开箱即用而您的自定义格式不能(source code)。

    尝试将其添加到初始化程序中或注册 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 内部的方法冲突。

    这里有一篇优秀的博文详细解释了构建自定义 Renderershttp://beerlington.com/blog/2011/07/25/building-a-csv-renderer-in-rails-3/

    【讨论】:

    • 太棒了!这就像一个魅力。不用担心名称,custom 只是一个占位符,但感谢关键字提示。
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-08
    • 2011-05-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多