Search code examples
ruby-on-railsruby-on-rails-3counter-cache

Cache counter column is not saving the recalculated value


I messed up the counter cache columns in my users table. I tried re-calculating it but its not saving the values.

This is not working:

User.update_all("boards_count=(Select count(*) from boards where boards.user_id=users.id)")

Not even this one:

 User.all.each do |user|
     user.boards_count = user.boards.length 
     user.save // this is returning true but value is not reflected in the database.
 end 

Solution

  • Counter cache is read-only model's attribute.

    Try to use reset_counters ( http://apidock.com/rails/ActiveRecord/CounterCache/reset_counters ) or run raw sql using connection, something like ActiveRecord::Base.connection.execute("UPDATE ....")