mongid嵌入式文档回调

Gag*_*gan 6 ruby-on-rails callback mongoid

我有一个跟mongoid rails3的以下模型

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
Run Code Online (Sandbox Code Playgroud)

现在我使用嵌套表单立即保存人员和地址.

但是除了after/before_validation之外,不会触发地址的创建/更新回调之后/之前的所有回调

当从嵌套表单创建地址时,不会为地址触发创建/更新回调之后/之前的任何建议?

谢谢

Hol*_*est 28

您可以在父文档上使用cascade_callbacks:true:

embeds_one:child,cascade_callbacks:true


Ben*_*enB 5

Mongoid 仅触发执行持久性操作的文档的回调。

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