Pergunta

I was wondering if there was a way to trigger the after_save callback on an embedded_in object in Mongoid mapper.

Example:

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

I'm aware that if I call i.save after words, it will fire, however really hard to remember to do that throughout my code.

Also, calling user.images.create(:file => file) is not an option, because I do a check to make sure the same file isn't uploaded twice.

Foi útil?

Solução

The only real solution is to call save on the embedded document. Here's a way to have that done automatically:

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

More info here:

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

Outras dicas

Okay, this is an old question, but with latest Mongoid, you can use:

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

Cascading Callbacks

If you want the embedded document callbacks to fire when calling a persistence operation on its parent, you will need to provide the cascade callbacks option to the relation.

Cascading callbacks is only available on embeds_one and embeds_many relations.

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

band.save # Fires all save callbacks on the band, albums, and label.

Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top