Ruby on rails 如何更新Rails3中的计数器缓存?

Ruby on rails 如何更新Rails3中的计数器缓存?,ruby-on-rails,ruby-on-rails-3,associations,has-many,Ruby On Rails,Ruby On Rails 3,Associations,Has Many,我在Rails应用程序中有正常关联: CustomerAccount有许多订单 订单所属客户账户 现在,我在属于语句中添加了一个:counter\u cache=>true,并在CustomerAccount中添加了orders\u count列 迁移后,orders\u count列中的每个值都是0。如何更新所有这些值以获得正确的计数?在迁移文件中执行以下操作: class AddTasksCount < ActiveRecord::Migration def self.up

我在Rails应用程序中有正常关联:

  • CustomerAccount有许多订单
  • 订单所属客户账户
现在,我在
属于
语句中添加了一个
:counter\u cache=>true
,并在
CustomerAccount
中添加了
orders\u count


迁移后,
orders\u count
列中的每个值都是0。如何更新所有这些值以获得正确的计数?

在迁移文件中执行以下操作:

class AddTasksCount < ActiveRecord::Migration  
  def self.up  
    add_column :projects, :tasks_count, :integer, :default => 0  

    Project.reset_column_information  
    Project.all.each do |p|  
      p.update_attribute :tasks_count, p.tasks.length  
    end  
  end  

  def self.down  
    remove_column :projects, :tasks_count  
  end  
end  
class AddTaskScont0
Project.reset\u列\u信息
Project.all.each do|p|
p、 更新属性:任务计数,p.tasks.length
结束
结束
def自动关闭
删除列:项目,:任务\u计数
结束
结束

执行另一个迁移,该迁移的up块中包含以下内容:

CustomerAccount.all.each do |account| 
  account.update_attributes(:orders_count => account.orders.size)
end

模型是CustomerAccount,不是Project。这比我的好,我不知道
reset\u counters
方法。@MaxWilliams,这就是我们在这里的原因。很高兴能报答你,我从你的回答中学到了很多。
CustomerAccount.find_each do |customer_account|
  CustomerAccount.reset_counters(customer_account.id, :orders)
end