counter_cache 可以与 has_many 一起使用吗?
我正在努力向我的模型添加 counter_cache:
Users (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
任何想法设置错误。我希望 Org.users_count 返回该组织中用户数量的 counter_cache?
I'm working to add a counter_cache to my models:
Users (id, org_id)
Orgs (id, users_count)
But get the following error: ArgumentError (Unknown key(s): counter_cache):
class Org < ActiveRecord::Base
has_many :users, :counter_cache => true
class User < ActiveRecord::Base
belongs_to :org
Any ideas what is setup wrong. I would like Org.users_count to return the counter_cache for the # of users in that org?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
这是行不通的。您必须将 counter_cache 移至 own_to:
并将
users_count
字段添加到Org
模型中,然后 Rails 将为您更新该字段。不要忘记添加:default=>; 0
在迁移中,否则无法正常工作。如果您的应用程序中已经有一些数据并且想要同步计数器,您可以(在迁移后)运行如下所示的操作:
It doesn't work this way. You have to move the counter_cache to the belongs_to:
And add a
users_count
field to theOrg
model and then Rails will update the field for you. Don't forget to add a:default=> 0
in the migration, otherwise it won't work fine.If you have already some data in your app and you want to sync the counter, you can run (after the migration) something like the following: