2011-03-31 88 views
5

我有mongoid Rails3中mongid嵌入文档回调

class Address 
    include Mongoid::Document 
    embedded_in :person, :inverse_of => :address 
    after_validation :call_after_validation 
    before_validation :call_before_validation 
    before_update :call_before_update 
    after_update :call_after_update 
    after_create :call_after_create 
    before_create :call_before_create 

    field :address1 
    field :address2 

    private 
    def call_after_validation 
    puts "After validation callback fired." 
    end 

    def call_before_validation 
    puts "Before validation callback fired." 
    end 

    def call_before_update 
    puts "Before update callback fired." 
    end 

    def call_after_update 
    puts "After update callback fired." 
    end 

    def call_after_create 
    puts "After create callback fired." 
    end 

    def call_before_create 
    puts "Before create callback fired." 
    end 



end 

class Person 
    include Mongoid::Document 
    embeds_one :address 

    field :name 
end 

后面的模型现在我用嵌套形式保存个人和地址一次。

但毕竟/前创建/更新回调地址不会被触发,除了后/ before_validation

的任何建议,为什么后/前创建/更新从嵌套形式创建时回调不被解雇的地址?

感谢

+0

更新:我使用mongoid版本2.0.0 beta19 – Gagan 2011-04-01 03:01:41

回答

4

Mongoid只触发了持续行动是执行对文档的回调。

因此,在这种情况下,只有验证回调才会触发地址,因为Address是嵌入到Person中的。将为Person调用创建/更新回调。

+0

有什么办法或黑客通过嵌入式docs before_save/after_save回调将被触发或可以实现类似的动作。 – Gagan 2011-04-01 06:00:50

+0

不要这么想,但你可以在Person模型中添加一些代码来做你想做的事,是吗? – BenB 2011-04-17 13:02:13

25

您可以使用cascade_callbacks:真正的父文件:

embeds_one:孩子,cascade_callbacks:真

+0

谢谢!虽然通常这是设置没有必要,对于某些情况下,这是一个非常有用的东西.. – fifigyuri 2012-12-07 08:09:45

+0

谢谢。非常有用的答案。 – 2016-01-07 11:50:58