Rails 中的 ActiveRecord 序列化程序不适用于新添加的关联

ActiveRecord Serializer in Rails does not work with newly added associations

我正在尝试向 Rails 中的现有模型添加关联。这是我的两个模型和我非常简单的序列化程序:

user.rb
--------
class User < ApplicationRecord
before_create :confirmation_token
  # encrypt password
  # has_secure_password
......
  
  devise :database_authenticatable, :recoverable, :rememberable, :trackable, :validatable
  
  # Model associations
  has_many :parties, foreign_key: :created_by_id

......


party.rb
------------
class Party < ApplicationRecord
  # model association
  has_many :ticket_categories, dependent: :destroy
  belongs_to :user
......


class PartySerializer < ActiveModel::Serializer
  # attributes to be serialized
  attributes :id, :title, :created_by_id, :created_at, :updated_at, .........
  # model association
  has_many :ticket_categories
  belongs_to :user
end




schema.rb
-----------
ActiveRecord::Schema.define(version: 2020_07_20_130631) do

  # These are extensions that must be enabled in order to support this database
  enable_extension "plpgsql"

 create_table "parties", force: :cascade do |t|
    t.string "title"
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    ........
    t.bigint "created_by_id"
    t.index ["created_by_id"], name: "index_parties_on_created_by_id"
  end

  
  create_table "users", force: :cascade do |t|
    t.string "firstname"
    t.string "lastname"
    t.string "email"
  .......
  end



  .....
  add_foreign_key "parties", "users", column: "created_by_id"
end

当通过 API 查询用户时,我得到了预期的派对数据,但对于用户:null

一旦我想通过 API 创建一个新的派对,就会发生回滚并显示错误“已完成 422 无法处理的实体”。一旦我从派对模型中删除关联 belongs_to,它就会再次像往常一样工作,但我仍然没有工作的序列化器。

预期结果为:

   {
    "id": 78,
    "title": "some title."
    "created_by_id": 9,
    "created_at": "2020-07-20T13:13:44,947Z"
    "updated_at": "2020-07-20T13:13:44,947Z"
    "ticket_categories": [
        {
        ..........
        }
    ],
    "user": {
          // here the user data associated with the party object
             }
}

但是在模型 party.rb 中使用 belongs_to 我在使用序列化程序时通过 Postman 为用户获取 null,在尝试 post 新派对时甚至为 422:

    # POST /parties
  def create
      @party = current_user.parties.create!(party_params)
      current_user.increment!(:partiesCreated, 1)
      json_response(id: @party.id)
  end

在此先感谢您的帮助!!

如果您未指定任何选项,belongs_to 将查找具有默认名称的外键 – 因此 belongs_to :user 将查找 user_id。如果如您的代码所示,您想使用 created_by_id 作为外键,则需要执行 belongs_to :user, foreign_key: :created_by_id (类似于您为 has_many 设置的内容)。