Rails counter cache not updating

by  |  07-Aug-2016 02:58

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.

rails counter cache not updating-39

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.

Rails counter cache not updating

User
Du hoffst eine ganz besondere Person für eine heiße sexuelle Beziehung, oder eben ein schnelles Abenteuer zu finden?…
Nakedgirlsonline chat
User
Guess that its name speaks louder than any descriptions, huh? Are you ready for the best voyeur experience in your whole life? What makes this resource so different from other sites offering sex filmed by voyeurs is the incredible diversity of its scenes. …
online dating site with no subscription
User
Field workers often create Excel spreadsheets to track data and run their processes. Here's how Carlsberg Danmark centralized business process management, created an orderly system with consistent data, and saved hundreds of hours in backoffice time.…
Best sex dating websites

Community Discussion