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.
Bob is going to create a forum thread, so we can create from the association, and automatically set the user_id there if we use that association, and create that first thread like so.
And you will notice that the is automatically set to zero, and that works great, and we got that insert, and it set it to zero, and all of that, on a database leve, you'll notice that none of the parameters passed into the insert into was actually that zero, nothing that we had to do controlled that value, so the database level is setting that default to the column, which is nice, but you will also notice that we issued an update to that user, and we took that forum_threads_count` and we added one to it with this (COALESCE("forum_treads_count", 0) 1).
Bob is going to add Let's go do that a couple times for that thread, so I've created a bunch of those, and we'll use that to go back in later, and make sure we can then add a counter cache for Bob, all the users that we can keep track of how many posts they've made.
So we've created those in the database, but we don't have a counter cache, and we want to add it afterwards, and so this is where a lot of people will be adding counter caches.
So that is all we need on forum posts: app/models/forum_because we created that association as well.
So we have those, the user to a forum thread, and the user to a forum post, and we also have the user thread to the forum post.
And all of this is done on a database level so there's no ruby involved for incrementing or decrementing that column, which is really neat.
The letter u is our variable for Bob, and that's keeping that up to date on him as well, so that is all working super well, and giving us exactly what we want.