Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby on Rails counter cache error

I get the error Unknown key(s): counter_cache when trying to implement a counter cache column in my RoR app.

I implemented the model associations in this question: Model association question

Here's my migration:

class AddVideoVotesCountToVideos < ActiveRecord::Migration
  def self.up
    add_column :videos, :video_votes_count, :integer, :default => 0

    Video.reset_column_information
    Video.find(:all).each do |p|
      p.update_attributes :videos_votes_count, p.video_votes.length
    end
  end

  def self.down
    remove_column :videos, :video_votes_count
  end
end

However, after watching http://media.railscasts.com/videos/023_counter_cache_column.mov I thought that maybe I had to move :counter_cache => true into the VideoVote model after belongs_to :video. However, when I do that, I get the error:

wrong number of arguments (2 for 1)

What am I doing wrong?

like image 888
Justin Meltzer Avatar asked Mar 17 '11 19:03

Justin Meltzer


2 Answers

update_attribute not update_attribteS

p.update_attribute :videos_votes_count, p.video_votes.length

or with update_attributes:

p.update_attributes( :video_votes_count => p.video_votes.length )

UPD 1

:counter_cache => true should be at the VideoVote class:

class VideoVote < ActiveRecord::Base
  belongs_to :user
  belongs_to :video, :counter_cache => true
end
like image 154
fl00r Avatar answered Oct 05 '22 23:10

fl00r


To do counter_caching,you need to run the migration first that fills in the count columns BEFORE you include the counter_cache statement in the model. Once in the model, the columns are read only.

like image 28
Rajive Jain Avatar answered Oct 05 '22 23:10

Rajive Jain