我使用Rails 3.2.6
。当我尝试使计数器缓存时,不知何故我得到了这个错误。我该如何解决这个问题?我在这个应用上做了同样的事情,但不是在这个模型上。
我的代码或关联有什么问题?
命令 bundle exec rake db:migrate
== AddCommunityTopicsCountToCommunity: migrating =============================
-- add_column(:communities, :community_topics_count, :integer, {:default=>0})
-> 0.0635s
rake aborted!
An error has occurred, all later migrations canceled:
community_topics_count is marked as readonly
模型/community.rb
...
has_many :community_topics
...
模型/community_topic.rb
...
belongs_to :community, counter_cache: true
...
迁移文件
class AddCommunityTopicsCountToCommunity < ActiveRecord::Migration
def up
add_column :communities, :community_topics_count, :integer, :default => 0
Community.reset_column_information
Community.all.each do |p|
p.update_attribute :community_topics_count, p.community_topics.length
end
end
def down
remove_column :communities, :community_topics_count
end
end
class AddCommunityTopicsCountToCommunity < ActiveRecord::Migration
def up
add_column :communities, :community_topics_count, :integer, :default => 0
Community.reset_column_information
Community.all.each do |c|
Community.reset_counters(c.id, :community_topics)
end
end
end
当你添加一个conter_cache
,它是不可能更新它使用Rails设置为只读默认值
您可以通过将updated_attribute
替换为update_column
来绕过此操作,这将跳过任何验证或回调。
conter_cache
有自己的处理方法,详见文档
你可以用
Community.all.each do |p|
Community.reset_counters(p.id, :community_topics)
end