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.

Comments left...

  • Thanks, very useful

    Nico Orellana at 07 Jul 07 at 01:38

  • I knew I was missing something

    Matt at 18 Sep 07 at 05:44

  • 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 at 04 Dec 07 at 23:41

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

    Donny at 04 Dec 07 at 23:43

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

    fulvio at 29 Jan 08 at 19:46

  • How to add counter_cache if I have has_many_polymorphs? For example:

    I have model Topic and Articles:

    in Topic

    has_many_polymorphs :affiliateds, 
      :from => [:topics, :articles], 
      :through => :affiliations, 
      :dependent => :destroy, 
      :as => :affiliate

    How to add topics_count, articles_count?

    MyTaskHelper at 17 Nov 08 at 09:22

Got something to say?