开发者

has_many association, nested models and callbacks

I've got model A and model Attach. I'm editing my A form with nested attributes for :attaches. And when I am deleting all attaches from A via accepts_nested_attributes_for how can I get after_update/after_save callbacks for all of my nested models? Problem is that when I am executing callbacks in model A they are executed right AFTER model A is updated and BEFORE model Attach is updated, so I can't, for example, know if there is NO ANY attaches after I delete them all :).

Look for example: my callback after_save :update_status won't work properly after I delete all of my attaches.

model A
  after_save :update_status
  has_many :attaches
  accepts_nested_attributes_for 开发者_如何学JAVA: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

I am using rails 3 beta


From rubyonrails.org:

IMPORTANT: In order for inheritance to work for the callback queues, you must specify the callbacks before specifying the associations. Otherwise, you might trigger the loading of a child before the parent has registered the callbacks and they won‘t be inherited.

Isn't it your problem? You're specifying the association before the callback.


Ok, I've removed after_save callback from A to nested model Attach (after_destroy callback)

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
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜