Forum: Ruby on Rails Couter Cache for 2 Parents?

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Tony Tseng (Guest)
on 2006-01-16 10:32
(Received via mailing list)
Hi,
I've got a question about counter cache; here's my setup:
I have 3 model classes, A, B, and C.
A has many C.
B has many C.
C belongs to both A and B.

Now I'd like to keep counters of C in both A and B for performance
reasons.
According to the rails book, this doesn't seem to be possible, as the
counter
feature requires changes to be made through the object that maintains
the
collection (either A or B). So my question is, what's the best way to
accomplish
this? Has anybody solved this issue before?

Cheers,
Tony
Jules (Guest)
on 2006-01-16 16:59
I don't understand it. If you have C belongs to A and B, can't you do a
counter-cache for both?

If you do:

a = A.new
b = B.new
c = C.new

a.cs << c
b.cs << c

That will increment both counters, or not?

Jules
Tony Tseng (Guest)
on 2006-01-16 20:55
That's the weird part. When I tried:
  a.cs << c
  b.cs << c

The result I got is:
a.cs_count = 1
b.cs_count = 2

However, if I access b.cs_count right before b.cs << c, then the count
is correct. (e.g., print out the value of b.cs_count before adding c to
b.cs)

I must be missing something here. Any suggestions?

Jules wrote:
> I don't understand it. If you have C belongs to A and B, can't you do a
> counter-cache for both?
>
> If you do:
>
> a = A.new
> b = B.new
> c = C.new
>
> a.cs << c
> b.cs << c
>
> That will increment both counters, or not?
>
> Jules
Nick S. (Guest)
on 2006-01-17 03:01
(Received via mailing list)
I have this same setup, and here's what worked for. Basically I added
the object a bit differently to the parents.
All I did for new new object was to set the parent instead of adding
it as a child. So in your case:

c.a_type = a
c.b_type = b

c.save

And the counts got updated correctly. It worked for me. And doing
c.destroy got decremented the count as needed.

-Nick
This topic is locked and can not be replied to.