Serializing the errors hash in ActiveModel::Serializer

后端 未结 4 1158
囚心锁ツ
囚心锁ツ 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 13:55

    I believe that the problem in this case is that for the failed status you won't call render with an object, like for created status.

    You can use a custom Serializer when calling render, for this case you can probably use something like

    if resource.errors.any?
      render serializer: ErrorSerializer, json: {:status => 'failed', :errors => resource.errors}
    else
      render json: {:status => 'created', :object => resource}
    end
    

    Give it a try and keep us informed of the result :)

提交回复
热议问题