【问题标题】:activemodel serializers with data as root when object is failed to save当对象保存失败时,以数据为根的 activemodel 序列化程序
【发布时间】:2016-01-21 20:09:46
【问题描述】:

我正在为我的 api 使用 activemodel 序列化程序来序列化数据模型。

class Api::V1::UsersController < Api::V1::ApiController
  include ::ActionController::Serialization

  def create
    user = User.new(user_params)
    if user.save
      return render json: user, status: :ok, root: :data
    end
    render_error(user.errors)
  end

  private

    def user_params
      params.require(:user).permit(:email, :password)
    end

    def render_error(errors, status = :unprocessable_entity)
      meta = { count: errors.messages.count }
      render json: errors, status: status, meta: meta, root: :data
    end
end

当用户参数有效并保存到db时,api以root身份返回数据。例如:

{
  "data": {
    "id": 11
  }
}

但是,当参数无效且用户对象未保存到数据库时,它会以 root 身份返回无数据。示例:

{
  "email": [
    "has already been taken"
  ]
}

我不确定我错过了什么,但我只想让 api 以 root 身份返回数据,以应对同样失败的情况。顺便说一句,用户序列化程序只包含 id 属性。

【问题讨论】:

    标签: ruby-on-rails ruby active-model-serializers


    【解决方案1】:

    你可以在json中指定:

    def render_error(errors, status = :unprocessable_entity)
      meta = { count: errors.messages.count }
      render json: { data: errors }, status: status, meta: meta
    end
    

    【讨论】:

      猜你喜欢
      • 2012-06-30
      • 2018-04-04
      • 2012-06-20
      • 2016-04-08
      • 2020-08-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多