Skip to content

Counter_cache in ruby on rails 1.2.2

Posted on 08 June 2007

I came across a rather odd Rails gotcha today whilst trying to use the counter_cache method.

Counter cache is a magic field that you can use with belongs_to relationships to keep a count of how many related objects the parent has. In my case, how many photos a job has.

Basically everything was getting saved ok, but the counter wasn't getting updated until I discovered that I needed to reload the job object after i'd created the association and before the save.

def add    
    @photo = Photo.new(params[:photo])    
    return unless request.post?
    @job.photos << @photo
    @job.reload
    if @job.save    
      redirect_to photos_url
      flash[:notice] = "Photo uploaded"
    end
  end

I can only assume it is something Rails 1.2.2 related as i've definitely used counter_cache without the extra reload step in the past and it's not detailed in any examples of its' usage.

The reload feels like quite a dirty fix, but it does the job, hopefully this will save someone else the time I wasted trying to figure this out.

View the snippets archive ››

5 comments made

Nico Orellana commented on 07 Jul 07 at 01:38

Thanks, very useful

Matt commented on 18 Sep 07 at 05:44

I knew I was missing something

donny commented on 04 Dec 07 at 23:41

I have the following error. Any help would be appreciated.

ActiveRecord::StatementInvalid: Mysql::Error: Unknown column ‘blog/comments_count’ in ‘field list’: UPDATE blog_posts SET `blog/comments_count` = `blog/comments_count` + 1 WHERE (`id` = 1)

I have the following class:

class Blog::Post < ActiveRecord::Base set_table_name ‘blog_posts’

has_many :comments, :order => 'created_at ASC', :dependent => :destroy

end

—> I have a column in Blog::Post called ‘comments_counter’ class Blog::Comment < ActiveRecord::Base belongs_to :post, :counter_cache => true

end

I don’k know why

Donny commented on 04 Dec 07 at 23:43

column name is ‘comments_count’. sorry for the mispelling on the previous post.

fulvio commented on 29 Jan 08 at 19:46

See, adding that reload doesn’t work for me though.

Got something to say?

About

Paul is a web developer for Kyanmedia web agency. He's lucky enough to write in Ruby on Rails full-time and uses this site to post snippets of code.

Contact

my name at gmail.com

More snippets

Take a look in the archive

Need a website?

Contact my employer. Make sure to check out our portfolio of work.

Hosting

I recommend hostingrails.com