缓存计数器列未保存计算值

时间:2012-08-01 10:56:39

标签: ruby-on-rails ruby-on-rails-3 counter-cache

我弄乱了users表中的计数器缓存列。我尝试重新计算它但不保存值。

这不起作用:

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

甚至不是这个:

 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 

1 个答案:

答案 0 :(得分:2)

计数器缓存是只读模型的属性。

尝试使用reset_counters(http://apidock.com/rails/ActiveRecord/CounterCache/reset_counters)或使用连接运行原始sql,例如ActiveRecord::Base.connection.execute("UPDATE ....")