mongoid嵌入式文档回调

时间:2011-03-31 11:23:04

标签: 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

现在我使用嵌套表格一次保存人员和地址。

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

当从嵌套表单创建地址时,不会针对地址触发创建/更新回调之后/之前的原因吗?

由于

2 个答案:

答案 0 :(得分:28)

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

embeds_one:child,cascade_callbacks:true

答案 1 :(得分:4)

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

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