Jonathan Crawford
Jonathan Crawford

Reputation: 73

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

I'm experiencing some weirdness that didn't seem to be the case in ActiveRecord. Note that I'm working with a legacy database so I need to assign the foreign key on the users collection.

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

OK, that all looks good to me. But when I do the following on the console, a Company is created, but the User isn't saved with the companyId set on it.

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

Instead I have to add a #save call on user like so:

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

Shouldn't create_company save the User record?

Upvotes: 0

Views: 686

Answers (1)

mrzasa
mrzasa

Reputation: 23307

I think it's the intended behaviour. I haven't found in the docs (neiher mongoid not Active Record) that user should be saved in this case.

It will be saved in Active Record if you reverse assignment:

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

To use this in mongoid, you need to add :autosave option:

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

Upvotes: 1

Related Questions