2

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?

Andrew
  • 42,517
  • 51
  • 181
  • 281

2 Answers2

5

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.

noazark
  • 289
  • 6
  • 23
0

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.

Flov
  • 1,527
  • 16
  • 25