3

私はを使用して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

models / community.rb

...
has_many :community_topics
...

models / 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
4

3 に答える 3

3
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
于 2013-01-07T13:48:37.687 に答える
2

を追加するconter_cacheと、Railsを使用して更新することはできません。デフォルトでは読み取り専用に設定されています。

検証やコールバックをスキップするに置き換えることupdated_attributeで、これを回避できます。update_column

于 2013-01-07T13:34:06.180 に答える
2

conter_cacheには独自の対処方法があります。詳細についてはドキュメントを確認してください。

あなたの場合、次のようなものを使用できます

Community.all.each do |p|
  Community.reset_counters(p.id, :community_topics)
end
于 2013-01-07T13:42:13.897 に答える