你如何更新rails 3中的counter_cache?

时间:2014-11-20 11:20:58

标签: ruby-on-rails ruby-on-rails-3 associations has-many

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

  • CustomerAccount has_many :orders
  • Order belongs_to :customer_account

现在,我在:counter_cache => true语句中添加了belongs_to,并将orders_count列添加到CustomerAccount

迁移后,orders_count列中的每个值都为0.如何更新所有这些值以获得正确的计数?

3 个答案:

答案 0 :(得分:1)

CustomerAccount.find_each do |customer_account|
  CustomerAccount.reset_counters(customer_account.id, :orders)
end

答案 1 :(得分: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  

答案 2 :(得分:0)

进行另一次迁移,其中包含以下内容:

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