Question

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 
Was it helpful?

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

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top