Forum: Ruby on Rails STI, HABTM & counter_cache

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.
Efe398b3b5436b0a8d4430090e8f86ea?d=identicon&s=25 seth b. (subimage)
on 2006-05-22 22:11
(Received via mailing list)
Hello world...

I have an interesting issue that the online docs aren't helping me with.

In my app I have 4 models

Item < ActiveRecord
Deal < Item
Product < Item
Category < ActiveRecord

Item has_and_belongs_to_many :categories...

On each category record I'd like to maintain a product_count and
deal_count
to increase performance. This doesn't appear possible with the current
"counter_cache" declaration.

Anyone have ideas on how to approach this?

In the past I've just run an hourly cron task to calculate & update all
records of this type, but I feel this probably isn't the most efficient
(or
accurate).

Ideas, comments?
3a18f0e7810b93223a39bf00c9d403b5?d=identicon&s=25 Frodo Larik (Guest)
on 2006-05-23 00:31
(Received via mailing list)
On 5/22/06, subimage interactive <subimage@gmail.com> wrote:

> On each category record I'd like to maintain a product_count and deal_count
> to increase performance. This doesn't appear possible with the current
> "counter_cache" declaration.
>
> Anyone have ideas on how to approach this?

I don't know how heavy the updating or saving of the model data is,
but you can always use callbacks to do the counts before saving...

class Category < ActiveRecord::Base
   def before_save
       self.products_count = Product.count('id', :conditions =>
["category_id=?",self.id])
       self.deals_count     = Deal.count('id', :conditions =>
["category_id=?",self.id])
   end
end

--
Sincerely,

Frodo Larik
Efe398b3b5436b0a8d4430090e8f86ea?d=identicon&s=25 seth b. (subimage)
on 2006-05-23 01:23
(Received via mailing list)
That's not even where the updating will happen. This would work in a
lazy
fashion, but I was just looking to see if I overlooked anything in AR
that
would do it for me.

Currently I have a cron script that runs (just to make sure the numbers
are
right), plus my own add/remove category methods on Item that update the
counts manually.
Efe398b3b5436b0a8d4430090e8f86ea?d=identicon&s=25 seth b. (subimage)
on 2006-05-23 09:20
(Received via mailing list)
Figured out a nice way to handle this for those of you who search it out
later.

There are 2 methods you can call on HABTM relationships "after_add" and
"after_remove". I'm calling update_counts from there.
This topic is locked and can not be replied to.