trigging after_save on an embedded item when assigning it via '<<' in mongoid?

匆匆过客 提交于 2019-12-08 01:41:08

问题


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.


回答1:


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




回答2:


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.



来源:https://stackoverflow.com/questions/3498796/trigging-after-save-on-an-embedded-item-when-assigning-it-via-in-mongoid

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!