Rails 5 列名为根的行为不端

Rails 5 Column Named Root Misbehaving

我正在尝试在 Rails 中创建一个 restful API 5,我的 类 之一有一个名为 root 的属性。这个根属性导致了一些错误,我将提供一个例子。 root 是 rails 或 ruby 中受保护的属性名称吗?

class ObjectsController < ApplicationController
  before_action only: %i[create]

  def create
    @object = Object.create(object_params)
    render json: @object
  end

  private


  def object_params
    params.require(:object).permit(:id, :root)
  end

当我post到/objects/ 类似以下内容:

{"object": {"id": "manual_id" , "root": "manual_root"}}

我在 Postman 中返回了以下内容:

{
    "id": "manual_id",
    "root": null,
    "extension": "manual_extension"
}

但在 MySQL 数据库中,root 的值为 manual_root。 有没有人知道问题可能是什么。

解决方案是像这样向模型添加属性别名:

class Object < ApplicationRecord
  alias_attribute :object_root, :root
end

并在对象序列化器中使用此属性class:

class ObjectSerializer < ActiveModel::Serializer
  attributes :id, :object_root
end

所以我的问题出在活动模型序列化程序上,我相信 root 是保留关键字。这是一个类似的问题:https://github.com/rails-api/active_model_serializers/issues/1135