Forum: Ruby on Rails counter_cache reference/tutorial

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.
Eb159164502bc1e2efb75ca7172805a0?d=identicon&s=25 Jeffrey L. Taylor (Guest)
on 2006-03-12 02:08
(Received via mailing list)
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
7448223373b57c5ff5683dc7be9edffe?d=identicon&s=25 Brett Rogers (Guest)
on 2006-03-12 02:23
(Received via mailing list)
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
Eb159164502bc1e2efb75ca7172805a0?d=identicon&s=25 Jeffrey L. Taylor (Guest)
on 2006-03-12 05:56
(Received via mailing list)
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 Rogers <brett.a.rogers@gmail.com>:
> > I'm trying to use counter_cache, but I'm not doing something right.
> >
This topic is locked and can not be replied to.