Mongoid: embedded documents automatically initializing on construction of parent
Asked Answered
M

2

5

Is there a way to get embedded documents to initialize automatically on construction in mongoid? What I mean is given that User which embeds a garage document. I have to write the following code to fully set up the user with the garage:

user = User.create!(name: "John")
user.build_garage
user.garage.cars << Car.create!(name: "Bessy")

Is there a way I can skip calling user.build_garage?

Thanks

Muscat answered 9/11, 2011 at 5:48 Comment(0)
D
6

You can add a callback to the User model like this:

class User
  ...
  after_initialize do |u|
    u.build_garage unless u.garage
  end
  ...
end

This callback fires after each instantiation of the class, so it fires after 'find' and 'new'.

Digger answered 9/11, 2011 at 9:43 Comment(5)
Is firing after find a good idea because doesn't that mean it will overwrite the previous embedded document?Muscat
Are there any mongoid autos that do this for the user?Muscat
I edited the answer to fix your first point. No, there are no automatisms for that. I would say that such functionality belongs to the actual application code.Digger
Dude. You rock! I was trying to use the initialize method to do this. Even though I was calling super first, the condition was failing and adding an extra doc. I'd add that maybe you should add a garage.exists? to that unlessWizard
Mongoid 3 now has an option for this, autobuildErlking
R
12

Mongoid 3 have autobuild option which tells Mongoid to instantiate a new document when the relation is accessed and it is nil.

embeds_one :label, autobuild: true
has_one :producer, autobuild: true
Ronen answered 30/9, 2013 at 7:36 Comment(0)
D
6

You can add a callback to the User model like this:

class User
  ...
  after_initialize do |u|
    u.build_garage unless u.garage
  end
  ...
end

This callback fires after each instantiation of the class, so it fires after 'find' and 'new'.

Digger answered 9/11, 2011 at 9:43 Comment(5)
Is firing after find a good idea because doesn't that mean it will overwrite the previous embedded document?Muscat
Are there any mongoid autos that do this for the user?Muscat
I edited the answer to fix your first point. No, there are no automatisms for that. I would say that such functionality belongs to the actual application code.Digger
Dude. You rock! I was trying to use the initialize method to do this. Even though I was calling super first, the condition was failing and adding an extra doc. I'd add that maybe you should add a garage.exists? to that unlessWizard
Mongoid 3 now has an option for this, autobuildErlking

© 2022 - 2024 — McMap. All rights reserved.