Mohit Jain
Mohit Jain

Reputation: 43959

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 

Upvotes: 0

Views: 373

Answers (1)

dimuch
dimuch

Reputation: 12818

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 ....")

Upvotes: 2

Related Questions