Search code examples
ruby-on-railsmongodbinitializationmongoidembedded-database

Mongoid: embedded documents automatically initializing on construction of parent


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


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