Search code examples
ruby-on-railsruby-on-rails-3counter-cache

Why do I get this error if I try to make counter cache?


I'm using Rails 3.2.6. When I try to make counter cache, I get this error somehow.
How can I fix this? I've done the same thing on this app but not on this model.
What's wrong with my code or association?

command bundle exec rake db:migrate

Log

==  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

models/community.rb

...
has_many :community_topics
...

models/community_topic.rb

...
belongs_to :community, counter_cache: true
...

migration file

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

Solution

  • 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