ruby-on-rails - 当对象保存失败时,以数据为根的 activemodel 序列化器

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

我正在为我的 API 使用事件模型序列化器来序列化数据模型。

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

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

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

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

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

我不确定我错过了什么,但我只是希望 API 以 root 身份返回失败场景的数据。顺便说一句,用户序列化程序仅包含 id 属性。

最佳答案

您可以在 JSON 中指定它:

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

关于ruby-on-rails - 当对象保存失败时,以数据为根的 activemodel 序列化器,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34933357/

相关文章:

ruby-on-rails - 主动模型串行器扁平结构

mysql - 将 sql 查询转换为 Activerecord 查询 Rails 4

ruby-on-rails - Rails,如何在设定的时间(早上)获得 1.day.from_now?

ruby - 将记录的 created_by 字段检索到 Rails3 中传递的月份和年份?

ruby - Thread#run 和 Thread#wakeup 之间的区别?

ruby-on-rails - 删除事件模型序列化程序中的日志消息

ruby-on-rails - 使用 ActiveModel::Serializer 如何向每个模型添加表属性

mysql - 在 Rails 中使用变异元音作为数据库密码

ruby-on-rails - 使用rspec测试Rails的嵌套属性

带有 ljust/rjust/center 的 Ruby 数组