Counter_cache, has_many and belongs_to

I am a bit confused about counter_cache here. The API docs


say that only the belongs_to association can take the :counter_cache
option. When I try to use it on a has_many I get an “unknown key(s):
counter_cache” error.

Why would this be the case? belongs_to means that this model has a
field with an id of a record form another table. belongs_to
associations only ever return a single object. So why would you need to
cache the number of associated objects? Wouldnt the has_many
association need the counter cache instead since you never know how many
records are linked?

Maybe I’m just not understanding something, but here is the snippet I am
using:

class Coupon
has_many :coupon_uses, :counter_cache => :uses_count
end

Now I could just do “coupon.coupon_uses.size” but there will be very
large number of associated objects and would rather not even visit the
table if I don’t need to.

Alex W. wrote:

I am a bit confused about counter_cache here. The API docs
http://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html
say that only the belongs_to association can take the :counter_cache
option. When I try to use it on a has_many I get an “unknown key(s):
counter_cache” error.

Why would this be the case? belongs_to means that this model has a
field with an id of a record form another table. belongs_to
associations only ever return a single object. So why would you need to
cache the number of associated objects? Wouldnt the has_many
association need the counter cache instead since you never know how many
records are linked?

Maybe I’m just not understanding something, but here is the snippet I am
using:

class Coupon
has_many :coupon_uses, :counter_cache => :uses_count
end

Now I could just do “coupon.coupon_uses.size” but there will be very
large number of associated objects and would rather not even visit the
table if I don’t need to.

Ah hah!

Since the counter cache gets updated when the child object saves, the
counter_cache call has to be there. The parent object doesnt need to
know about it. The counter caching behaviour is in the child even
though the actual data field is in the parent. This make my code more
like.

class Coupon
has_many :coupon_uses
end

class CouponUses
belongs_to :coupon, :counter_cache => :uses_count
end

This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.

| Privacy Policy | Terms of Service | Remote Ruby Jobs