has_many关联,嵌套模型和回调

时间:2010-05-10 14:28:41

标签: ruby-on-rails ruby callback

我有模型A和模型附件。我正在使用嵌套属性编辑我的A表单:attach。当我通过accepts_nested_attributes_删除A中的所有附件时,如何为所有嵌套模型获取after_update / after_save回调?问题是,当我在模型A中执行回调时,它们会在模型A更新之后立即执行,并且BEFORE模型附加更新后,所以我不能,例如,在我删除它们之后知道是否没有任何附件:)

查看示例:删除所有附件后,我的回调after_save :update_status将无法正常工作。

model A
  after_save :update_status
  has_many :attaches
  accepts_nested_attributes_for :attaches, :reject_if => proc { |attributes| attributes['file'].blank? }, :allow_destroy => true

  def update_status
    print "\n\nOUPS! bag is empty!\n\n" if self.attaches.empty?
  end
end

model Attach
  belongs_to A
end

我正在使用rails 3 beta

2 个答案:

答案 0 :(得分:2)

来自rubyonrails.org

  

重要:为了让继承适用于回调队列,您   必须先指定回调   指定关联。   否则,你可能会触发   在父母之前加载孩子   已经注册了回调和他们   不会被继承。

这不是你的问题吗?您在回调之前指定了关联。

答案 1 :(得分:0)

好的,我已将A的after_save回调移除到嵌套模型Attach(after_destroy回调)

model A
  has_many :attaches
  accepts_nested_attributes_for :attaches, :reject_if => proc { |attributes| attributes['file'].blank? }, :allow_destroy => true
end

model Attach
  after_destroy :update_status
  belongs_to :a

  def update_status
    print "\n\nOUPS! bag is empty!\n\n" if self.a.attaches.empty?
  end
end