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?
On 5/22/06, subimage interactive [email protected] 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 L.
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.
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.