counter_cache可以和has_many一起使用吗?
我正在努力为我的模型添加一个counter_cache:
用户(id,org_id)Orgs(id,users_count)
但是得到以下错误: ArgumentError (Unknown key(s): counter_cache):
class Org true class User < ActiveRecord::Base belongs_to :org
什么设置错误的任何想法。 我想Org.users_count为该组织中的#个用户返回counter_cache?
这不起作用。 您必须将counter_cache移动到belongs_to:
class User < ActiveRecord::Base belongs_to :org, :counter_cache => true end
并将一个users_count
字段添加到Org
模型,然后Rails将为您更新该字段。 不要忘记在迁移中添加:default=> 0
,否则它将无法正常工作。
如果您的应用中已有一些数据并且您想要同步计数器,则可以运行(迁移后)类似以下内容:
Org.find(:all).each do |o| Org.update_counters o.id, :users_count => o.users.count end