![](/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.