counter_cache可以和has_many一起使用吗?

AnA*_*ice 5 ruby-on-rails ruby-on-rails-3

我正在为我的模型添加一个counter_cache:

用户(id,org_id)Orgs(id,users_count)

但是得到以下错误: ArgumentError (Unknown key(s): counter_cache):

class Org < ActiveRecord::Base
   has_many :users, :counter_cache => true

class User < ActiveRecord::Base
   belongs_to :org
Run Code Online (Sandbox Code Playgroud)

什么设置错误的任何想法.我想Org.users_count为该组织中的#个用户返回counter_cache?

luc*_*tte 15

它没有这种方式.您必须将counter_cache移动到belongs_to:

class User < ActiveRecord::Base
   belongs_to :org, :counter_cache => true
end
Run Code Online (Sandbox Code Playgroud)

users_countOrg模型中添加一个字段,然后Rails将为您更新字段.不要忘记:default=> 0在迁移中添加一个,否则它将无法正常工作.

如果您的应用中已有一些数据并且您想要同步计数器,则可以运行(迁移后)类似以下内容:

  Org.find(:all).each do |o|
    Org.update_counters o.id, :users_count => o.users.count
  end
Run Code Online (Sandbox Code Playgroud)