Question

I have a model called Entity and the create action in the controller looks like this:

# enitities_controller.rb
def create
   # loading params, etc...
   @entity.save
   respond_with @entity
end

I am using jbuilder for custom JSON views rather than rendering @entity.to_json, which works great. I have one last issue, which is when the model won't save due to validation errors I get the following response (with status 422 Unprocessable Entity):

{"errors":{"parent_share":["can't be blank","is not a number"]}}

I would like to override this json with my own. I am aware of he possibility to replace respond_with @entity with:

respond_with @entity do |format|
  if @entity.errors.any?
    format.json {
      render "entities/create", :status => :unprocessable_entity
    }
  end
end

But shouldn't there be a more auto-magic way by defining some sort of errors view or something? This feels a bit dirty AND it makes me have to write more code each time I need this rather than allowing me to use respond_with. Is there another way?

Était-ce utile?

La solution

Meanwhile I have found the answer:

You have to create the file lib/application_responder.rb and add the following:

class ApplicationResponder < ActionController::Responder
  include Responders::FlashResponder
  include Responders::HttpCacheResponder

  def to_json
    set_flash_message! if set_flash_message?
    if !has_errors? || response_overridden?
      default_render
    else
      controller.default_render( status: :unprocessable_entity )
    end
  end

end

And add the following to your application responder:

self.responder = ApplicationResponder

What this does is add a to_json method that will copy the behaviour of the to_js responder.

Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top