Simply Rails 2 - Counter Cache - please help!

Hi all,

I’m currently working through Simply Rails 2 and have come across a problem when trying to implement the Counter Cache in chapter 9.

After following the counter cache instructions (which I’ve now gone through 3 times! and checked against the source code from SitePoint) I get this error when attempting to load the Stories page in Shovell

ActiveRecord::StatementInvalid in StoriesController#index

SQLite3::SQLException: no such column: votes_count: SELECT * FROM stories WHERE (votes_count >= 1) ORDER BY id DESC

Could anyone give me some pointers as to where I might be going wrong? Obviously the column hasn’t been created by my AddCounterCacheToStories migration file but I don’t know why.

When I run db:migrate AddCounterCacheToStories (which I think would only migrate this file - sorry newbie!) then I get the error "rake aborted! Don’t know how to build task ‘AddCounterCacheToStories’.

The code in the file is;

class AddCounterCacheToStories < ActiveRecord::Migration
  def self.up
    add_column :stories, :votes_count, :integer, :default => 0
	Story.find(:all).each do |s|
	  s.update_attribute :votes_count, s.votes.length
	end
  end

  def self.down
    remove_column :stories, :votes_count
  end
end

Check your schema.rb file to see if your data structure is right. Sounds like the migration is failing.

Sorry for the late reply!

Yes the column isn’t in the schema.rb because the migration fails. I’ve gone through the previous chapter of the book again and I get the same error on the Counter Cache section!

“When I run db:migrate AddCounterCacheToStories”

You should just be able to run “rake db:migrate”, no? At least that’s how it’s done in rails 3…

You shouldn’t need to specify the name of the migration I don’t think