Run after_save in an inline element when assigning it via "<<" in a mangoid?

I was wondering if there is a way to call the after_save callback for the embedded_in object in the Mongoid mapper.

Example:

 i = Image.new(:file => file) user.images << i # => i.after_save should be triggered here 

I know that if I call i.save after the words, it will start, however it is very difficult to remember this in all my code.

Also, calling user.images.create(:file => file) not an option, because I check to make sure that the same file does not load twice.

+2
source share
2 answers

The only real solution is to call save into the embedded document. Here you can do it automatically:

 class User references_many :images do def <<(new_elm) returner = super new_elm.save returner end end end 

More details here:

https://github.com/mongoid/mongoid/issues/173

+2
source

Ok, this is an old question, but with the last mongoid you can use:

http://mongoid.org/en/mongoid/docs/relations.html

Cascading callbacks

If you want embedded document callbacks to be triggered when the save operation is called on the parent element, you need to provide the cascading callback parameter for the relationship.

Cascading callbacks are only available for embeds_one and embeds_many .

 class Band include Mongoid::Document embeds_many :albums, cascade_callbacks: true embeds_one :label, cascade_callbacks: true end 

band.save # Runs all saved callbacks in a group, albums, and shortcuts.

+3
source

All Articles