简体   繁体   中英

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 associated 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM