Question

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
Was it helpful?

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

OTHER TIPS

When you add a conter_cache, it's not possible to updated it using Rails set it as read-only by default.

You can bypass this by replacing updated_attribute with update_column, which skips any validation or callbacks.

conter_cache has its own methods to deal with, check the docs for details.

In your case you can use something like

Community.all.each do |p|
  Community.reset_counters(p.id, :community_topics)
end
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top