2012-04-16 53 views
2

在Rails的3.2.x中使用Rabl的,下面給出的控制器操作:Rails的Rabl的respond_with錯誤模板

respond_to :html, :json 

def create 
    @foo = Foo.create(params[:foo]) 
    respond_with @foo 
end 

假設驗證失敗,你怎麼respond_with使用Rabl的模板,而不是標準的JSON哈希的錯誤 - IE。除了與請求一起發回的驗證錯誤消息之外,我還想要其他模型屬性。

對此提出建議?

回答

5

我發現這一個困難的方式。你應該爲你的應用程序控制器創建一個自定義的響應者,或者至少你的個人響應。有關更多詳細信息,請參見Three reasons to love ActionController::Responder

我的解決辦法:

# app/responders/api_responder.rb 
class ApiResponder < ActionController::Responder 
    def to_format 
    case 
    when has_errors? 
     controller.response.status = :unprocessable_entity 
    when post? 
     controller.response.status = :created 
    end 

    default_render 
    rescue ActionView::MissingTemplate => e 
    api_behavior(e) 
    end 
end 

# app/controllers/application_controller.rb 
class ApplicationController < ActionController::Base 
    #... 
    self.responder = ApiResponder 
    #... 
end 

你也可以使用respond_with @foo, responder: ApiResponder代替。

感謝haxney送我正確的方向。

+0

我喜歡它。謝謝 :) – Andrew 2012-05-15 01:02:24

0

我想,您需要刪除控制器頂部的respond_to調用,並在動作中刪除respond_with調用以使rabl呈現您的rabl模板。

只需在每個不需要RABL的操作結束時添加respond_to塊即可。