Rails RABL respond_with error template

二次信任 提交于 2019-12-22 13:58:10

问题


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

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.

Suggestions?


回答1:


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.




回答2:


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.



来源:https://stackoverflow.com/questions/10168536/rails-rabl-respond-with-error-template

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