Rails RABL respond_with error template

时间秒杀一切 提交于 2019-12-06 11:24:46

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.

My solution:

# 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

You could also use respond_with @foo, responder: ApiResponder instead.

Thanks to haxney for sending me in the right direction.

I guess, you need to remove the respond_to call at the top of the controller and remove the respond_with call within the action to get rabl render your rabl template.

Just add a respond_to block at the end of each action where you don't need RABL.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!