2014-02-26 23 views
1

當試圖獲取自定義輸出與respond_to/with一起行爲時,我會得到一個ActionView :: MissingTemplate,就像它表現xml/json輸出一樣。在Ruby on Rails中設置respond_to和respond_with的自定義格式4

我有我的對象上可用的自定義輸出格式。

@item.to_custom 

我已經登記在mime_types.rb註冊自定義的Mime ::類型的格式。

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 /視圖/ show.custom.ruby修復:

@item.to_custom 

有沒有辦法讓to_custom像to_xml或to_json工作中的respond_to /帶設置?只需使用to_custom方法而不需要模板?或者我將不得不使用明確調用方法的視圖模板?

回答

3

如果您希望在未明確添加視圖模板的情況下進行渲染,則需要爲自定義格式手動添加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/

+0

太好了!這工作像一個魅力。不用擔心這個名字,custom只是一個佔位符,但是感謝關鍵詞的提升。 – Charlie