counter_cache 可以与 has_many 一起使用吗?

发布于 2025-01-08 07:10:51 字数 390 浏览 0 评论 0原文

我正在努力向我的模型添加 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

吻泪 2025-01-15 07:10:51

这是行不通的。您必须将 counter_cache 移至 own_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

It doesn't work this way. You have to move the counter_cache to the belongs_to:

class User < ActiveRecord::Base
   belongs_to :org, :counter_cache => true
end

And add a users_count field to the Org 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:

  Org.find(:all).each do |o|
    Org.update_counters o.id, :users_count => o.users.count
  end
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文