Mongoid 未在 `create_#{association}` 方法调用中将关联保存到 `belongs_to` 关联

Mongoid not saving association to `belongs_to` association on `create_#{association}` method call

我遇到了一些奇怪的事情,而在 ActiveRecord 中似乎并非如此。请注意,我正在使用遗留数据库,因此我需要在 users 集合上分配外键。

class User
  include Mongoid::Document
  include Mongoid::Timestamps

  belongs_to :company, foreign_key: "companyId"
end

class Company
  include Mongoid::Document
  include Mongoid::Timestamps

  has_many :users
end

好的,我觉得一切都很好。但是当我在控制台上执行以下操作时,会创建一个 Company,但是 User 不会与 companyId 设置一起保存。

user.create_company(name: "My cool company")

相反,我必须像这样在 user 上添加一个 #save 调用:

user.create_company(name: "My cool company")
user.save

不应该 create_company 保存 User 记录吗?

我认为这是预期的行为。我没有在文档中发现 user 应该在这种情况下保存。

反向赋值会保存在Active Record中:

company = Company.create(name: 'My cool company')
company.users << user

要在 mongoid 中使用它,您需要添加 :autosave 选项:

One core difference between Mongoid and Active Record from a behavior standpoint is that Mongoid does not automatically save child relations for relational associations. This is for performance reasons. Docs

class Company
  include Mongoid::Document
  include Mongoid::Timestamps

  has_many :users, autosave: true
end