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
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 -- Posted via http://www.ruby-forum.com/.
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-- Posted via http://www.ruby-forum.com/.
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 On 1/16/06, Tony Tseng <tony.t.tseng@gmail.com> wrote:> 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 > > > -- > Posted via http://www.ruby-forum.com/. > _______________________________________________ > Rails mailing list > Rails@lists.rubyonrails.org > http://lists.rubyonrails.org/mailman/listinfo/rails >