Rails counter cache not updating
Adding a counter cache to a has_many/belongs_to Active Record relationship after the underlying records have been around awhile is one of those tasks that tends to trip up Rails newbies.Here's an example migration showing the necessary steps.Although the mechanism built into Rails does the hard part, you still have to implement perform a couple of steps or else it won’t work at all.
Posts keep the count of their tags: class Tagging # FIELDS: post_id, tag_id belongs_to :tag belongs_to :post, counter_cache: :tags_count # updates tags_count in Post end class Tag # FIELDS: title has_many :taggings has_many :posts, through: :taggings, dependent: :destroy end class Post # FIELDS: content, tags_count has_many :taggings has_many :tags, through: :taggings, dependent: :destroy end field will be automatically updated any time a post is created, updated or deleted.
Counter cache works by performing an SQL update each time a new association is created or deleted.
I think it's not possible any more in rails edge (2.0) to fill the count-colums afterwards, because (from the edge api): "Note: Specifying a counter_cache will add it to that model’s list of readonly attributes using attr_readonly." Some other idea for this?
Beate, I recently posted about this very issue on my blog. Check it out: Thanks for the information about how to add a counter cache to an existing db However I found that solution a little bit to complex for me.
So with every Rails project that reached "medium size" (whatever that meant at the time), I started worrying about data consistency and I created a service that is executed automatically regularly (e.g.