Question

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

Was it helpful?

Solution

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'.

OTHER TIPS

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
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top