Serializing the errors hash in ActiveModel::Serializer

后端 未结 4 1165
囚心锁ツ
囚心锁ツ 2021-02-08 13:45

I\'m using ActiveModel::Serializer to customize the JSON responses for my API. This works fine in most cases, except when it fails to save a model successfully.

For exa

4条回答
  •  时光说笑
    2021-02-08 14:03

    The ErrorsSerializer doesn't work because of how responders create json response for errors:

    def json_resource_errors
      { errors: resource.errors }
    end
    

    (rails < 4.2 https://github.com/rails/rails/blob/4-1-stable/actionpack/lib/action_controller/metal/responder.rb#L290 for newer rails, responders have been extracted to https://github.com/plataformatec/responders/blob/master/lib/action_controller/responder.rb#L288)

    one way of dealing with this is to override this method for responders. Put this code in your config initializers:

    # config/initializers/action_controller_responder.rb
    module ActionController
      class Responder
        def json_resource_errors
          resource.errors
        end
      end
    end
    

    Then your serializer will work for resource errors.

提交回复
热议问题