This counter cache does not seem to be working correctly, although to my knowledge I have done everything correctly.
user.rb:
class User < ActiveRecord::Base
has_many :search_stats, counter_cache: true
end
migration:
class AddSearchStatsCounterCacheToUsers < ActiveRecord::Migration
def up
add_column :users, :search_stats_count, :integer, default: 0, null: false
User.reset_column_information
User.find_each do |u|
u.update_attribute(:search_stats_count, u.search_stats.count)
end
end
def down
remove_column :users, :search_stats_count
end
end
Why does this not update the counter?
user = User.find( user_id )
user.search_stats.create!( search_params: search_params.to_json )
Serious brain fart. The counter_cache
option should be on the belong_to
not the has_many
. Explicitly stated in the Rails docs