Rails RABL respond_with错误模板

在Rails 3.2.x中使用RABL,给出以下控制器操作:

respond_to :html, :json def create @foo = Foo.create(params[:foo]) respond_with @foo end 

假设validation失败,您如何获得respond_with以使用RABL模板而不是标准的JSON错误哈希 – IE。 除了与请求一起发回的validation错误消息之外,我还想要其他模型属性。

建议?

我发现了这个问题。 您应该为应用程序控制器创建自定义响应程序,或者至少为您的个人响应创建。 有关详细信息,请参阅喜欢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让我朝着正确的方向前进。

我想,您需要删除控制器顶部的respond_to调用并删除操作中的respond_with调用以获取rabl渲染您的rabl模板。

只需在每个不需要RABL的操作结束时添加一个respond_to块。