开发者

ruby on rails associations - removing something which doesn't exist in the association

So I have a model foo which has_and_belongs_to_many bar.

foo.bar gives me all the bars associated with foo. Every time I delete a bar, I call Foo.decrement_counter(:bar_count, self[:id]) via the :after_remove callback.

I am testing the removal of a bar which is not assoc开发者_开发知识库iated with foo. This too decrements the counter... which I don't want. How do I ensure that the counter is decremented only when a bar is actually deleted from the association?

has_and_belongs_to_many :bar, :after_remove => :dec_bar_count, :after_add => :inc_bar_count, :uniq => true

def dec_bar_count(record)
  Foo.decrement_counter(:bar_count, self[:id])
end

Thanks.


Why no just use Foo.bar.count

Maybe I'm misunderstanding what it is you're counting, but it seems like you're trying to duplicate the counting functionality already in ActiveRecord.

This question may also be related, regarding DB caching in Rails.

0

上一篇:

下一篇:

精彩评论

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

最新问答

问答排行榜