Rails RABL response_with错误模板 [英] Rails RABL respond_with error template
问题描述
在以下控制器操作下,在Rails 3.2.x中使用RABL:
Using RABL in Rails 3.2.x, given the following controller action:
respond_to :html, :json
def create
@foo = Foo.create(params[:foo])
respond_with @foo
end
假设验证失败,如何获取response_with以使用RABL模板而不是错误的标准JSON哈希-IE.除了与请求一起发送的验证错误消息外,我还需要其他模型属性.
Assuming the validation fails, how do you get respond_with to use a RABL template instead of the standard JSON hash of errors -- IE. I would like other model attributes besides the validation error message sent back along with the request.
建议?
推荐答案
我很难做到这一点.您应该为您的应用程序控制器或至少您的个人响应创建一个自定义响应器.请参阅爱ActionController :: Responder的三个原因更多细节.
I found this one out the hard way. You should create a custom responder for your application controller, or at least your individual response. See Three reasons to love ActionController::Responder for more details.
我的解决方案:
# 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
.
感谢哈克斯尼向正确的方向发送邮件给我.
Thanks to haxney for sending me in the right direction.
这篇关于Rails RABL response_with错误模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!