2010-11-29 89 views
11

我正在嘗試添加counter_cache,並且此Rails 3遷移給了我一個我似乎無法解決的錯誤。使用update_attribute運行Rails 3遷移時發生只讀錯誤

遷移是

 
class AddItemsCountToStore < ActiveRecord::Migration 
    def self.up 
     add_column :stores, :items_count, :integer, :default => 0 

     Store.reset_column_information 

     Store.all.each do |store| 
      store.update_attribute :items_count, store.items.count 
     end 
    end 

    def self.down 
     remove_column :stores, :items_count 
    end 
end 

和錯誤是:

== AddItemsCountToStore:遷移====================== =================== - add_column(:stores,:items_count,:integer,{:default => 0}) - > 0.0680s rake中止! 發生錯誤,這和所有後來遷移取消:

items_count被標記爲只讀 C:/Ruby192/lib/ruby/gems/1.9.1/gems/activerecord-3.0.0/lib/active_record/ persistence.rb:115:`update_attribute'

任何想法?

+0

[計數器\ _cache實現問題]的可能重複(http://stackoverflow.com/questions/4295404/problem-with-counter-cache-implementation) – mbillard 2014-04-30 11:03:16

回答