2012-04-16 63 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块即可。