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 ?
user.build_garage
thanks
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".
Mongoid 3 has an autobuild parameter that tells Mongoid to create a new document when accessing it and nil .
autobuild
nil
embeds_one :label, autobuild: true has_one :producer, autobuild: true
Source: https://habr.com/ru/post/1380333/More articles:Motorola Android 2.2 camera ignores EXTRA_OUTPUT parameter - javaHow do I improve Javascript / jQuery animations? - javascriptIs iOS5 ARC safe to schedule NSTimers from background selectors? - iosIs a DAO accessible only for accessing databases? - javaDisplaying data hierarchically using LINQ - c #String Comparison JPA - stringHow to get a numerical value from a string containing numbers and characters - javascriptR function call from C ++ on Windows - c ++WebSite standalone support - java-eeCreating projects in subfolders of [eclipse CDT] - eclipseAll Articles