Counter_cache reference/tutorial


#1

I’m trying to use counter_cache, but I’m not doing something right.
It is unreliable and I keep having to correct it manually. Is there a
good tutorial or reference on how to use it on-line? I have the AWDR
book, but I need something more complete.

TIA,
Jeffrey


#2

DHH shows how to use counters in this screencast as well as how to
properly
use migrations

http://media.rubyonrails.org/video/migrations.mov

regards,
Brett


#3

I think I am doing it the way the video and AWDR show. But something
is wrong. Here is my code:

app/models/items.rb:
class Item < ActiveRecord::Base
belongs_to :channel, :counter_cache => true
validates_presence_of :channel
end

app/models/channel.rb:
class Channel < ActiveRecord::Base
has_many :items
end

typical code that creates and destroys items (RSS aggregator):
channel.website_url = rss.channel.link
channel.description = rss.channel.description
rss.items.each do |item|
i = Item.find(:first, :conditions =>
[“title = ? and channel_id = ?”, item.title, channel.id])
if (i)
i.times_seen += 1
i.save!
else
i = channel.items.create(:title => item.title, :URL => item.link,
:description => item.description)
end
end
channel.items(:refresh).each do |item|
if (item.updated_at &&
(item.updated_at < Time.now.ago(@@RELOAD_INTERVAL/2))) then
logger.debug(“Expiring ‘#{item.title}’ created on
#{item.created_at}”)
item.destroy()
end
end

Something is clobbering channel.items_count, typically setting it to
zero.

TIA,
Jeffrey

Quoting Brett R. removed_email_address@domain.invalid:

I’m trying to use counter_cache, but I’m not doing something right.