Mongoid: inline documents are automatically initialized when the parent is built

Is there a way to get inline documents to automatically initialize a construct in mongoid? I mean the user who inserts the garage document. I have to write the following code to fully configure the user in the garage:

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

Is there a way to skip calling user.build_garage ?

thanks

+4
source share
2 answers

You can add a callback to the user model as follows:

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

This callback is triggered after each instance of the class, so it starts after "find" and "new".

+6
source

Mongoid 3 has an autobuild parameter that tells Mongoid to create a new document when accessing it and nil .

 embeds_one :label, autobuild: true has_one :producer, autobuild: true 
+11
source

Source: https://habr.com/ru/post/1380333/


All Articles