2010-05-10 118 views
1

我有模型A和模型附加。我正在编辑我的A表单,其嵌套属性为:attach。并且,当我通过accept_nested_attributes_for删除A中的所有附件时,如何才能为所有嵌套模型获取after_update/after_save回调?问题是,当我在模型A中执行回调时,它们会在模型A更新之后执行,并且BEFORE模型附加被更新,因此我无法知道在删除它们后是否有任何附加内容。 。has_many关联,嵌套模型和回调

例如:我删除了所有附件后,我的回调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 

我使用的轨道3测试版

回答

0

好吧,我after_save的回调函数删除从A嵌套模型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 
2

rubyonrails.org

重要:为了继承回调队列工作,你 前必须 指定指定回调协会。 否则,您可能会在父 已注册回调并且它们不会继承 之前触发 小孩的加载。

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

+0

良好的通知,但在我的真实模型回调代码之前指定 – fl00r 2010-05-10 14:51:46