Counter_cache in ruby on rails 1.2.2
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.
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
5 comments made
Thanks, very useful
I knew I was missing something
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’
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
column name is ‘comments_count’. sorry for the mispelling on the previous post.
See, adding that reload doesn’t work for me though.
Got something to say?