简体   繁体   English

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

[英]Setting up custom formats for respond_to and respond_with in Ruby on Rails 4

I'm getting a ActionView::MissingTemplate when trying to get a custom output to behave with respond_to/with like it behaves xml/json output. 当我尝试使用respond_to /来表示自定义输出时,我得到一个ActionView :: MissingTemplate ,就像它表现出xml / json输出一样。

I have a custom output format available on my object. 我的对象上有自定义输出格式。

@item.to_custom

I've registered the format with a custom Mime::Type registered in the mime_types.rb . 我已经在mime_types.rb中注册了自定义Mime :: Type的格式。

Mime::Type.register "application/custom", :custom

I have it listed in my respond_to options in my controller 我把它列在我的控制器的respond_to选项中

class ItemsController < ApplicationController
  respond_to :html, :xml, :custom

And then I have a respond_with method before the end of my show action. 然后我在show show结束前有一个respond_with方法。

def show
  @item = Item.find(params[:id])    
  respond_with(@item) 
end

When I access items/1234.xml I get the xml output. 当我访问items / 1234.xml时,我得到了xml输出。 When I try to access items/1234.custom I get an error ActionView::MissingTemplate . 当我尝试访问items / 1234.custom时,我得到一个错误ActionView :: MissingTemplate I can fix it by adding the file app/views/show.custom.ruby with the contents: 我可以通过添加文件app / views / show.custom.ruby来修复它:

@item.to_custom

Is there a way to get to_custom to work like to_xml or to_json in a respond_to/with setup? 有没有办法让to_custom在response_to / with setup中像to_xml或to_json一样工作? To just use the to_custom method without needing a template? 只需使用to_custom方法而不需要模板? Or will I have to use a view template that calls the method explicitly? 或者我是否必须使用明确调用该方法的视图模板?

You'll need to manually add a Renderer for your custom format if you want it to render without explicitly adding a view template. 如果要在不显式添加视图模板的情况下进行渲染,则需要手动为自定义格式添加Renderer

The Rails built-in formats xml and json have renderers automatically added from within the Rails framework, which is why they work right out of the box and your custom format does not ( source code ). Rails内置格式xmljson具有从Rails框架中自动添加的渲染器,这就是为什么它们开箱即用而你的自定义格式没有( 源代码 )。

Try adding this in an initializer or right below where you register your MIME type 尝试在初始化程序中或在您注册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

NOTE: Don't use custom as your format name because it will conflict with a method in the respond_with internals. 注意:不要使用custom作为格式名称,因为它将与respond_with内部中的方法冲突。

There is an excellent blog post that explains building custom Renderers in depth here: http://beerlington.com/blog/2011/07/25/building-a-csv-renderer-in-rails-3/ 有一篇很棒的博客文章解释了如何深入构建自定义Renderershttp//beerlington.com/blog/2011/07/25/building-a-csv-renderer-in-rails-3/

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM