【发布时间】:2015-11-23 09:16:12
【问题描述】:
尽管已经提出了类似的问题:
- counter_cache with has_many :through
- dependent => destroy on a "has_many through" association
- has_many :through with counter_cache
它们都没有真正解决我的问题。
我有三个模型,有一个 has_many :through 关联:
class User < ActiveRecord::Base
has_many :administrations
has_many :calendars, through: :administrations
end
class Calendar < ActiveRecord::Base
has_many :administrations
has_many :users, through: :administrations
end
class Administration < ActiveRecord::Base
belongs_to :user
belongs_to :calendar
end
join Administration 模型具有以下属性:
id
user_id
calendar_id
role
我想计算每个user 有多少个calendars,每个calendar 有多少个users。
我打算使用 counter_cache 如下:
class Administration < ActiveRecord::Base
belongs_to :user, counter_cache: :count_of_calendars
belongs_to :calendar, counter_cache: :count_of_users
end
(当然还有将:count_of_calendars 添加到users 表和:count_of_users 到calendars 表的相应迁移。)
但后来,我偶然发现了this warning in Rails Guides:
4.1.2.4:依赖
如果您将 :dependent 选项设置为:
- :destroy,当对象被销毁时,会在其关联对象上调用destroy。
- :delete,当对象被销毁时,其所有关联对象将直接从数据库中删除,而不调用它们的 销毁方法。
您不应该在 belongs_to 关联上指定此选项,该关联是 与另一个类的 has_many 关联连接。这样做可以 导致数据库中的孤立记录。
因此,计算每个user 有多少个calendars 以及每个calendar 有多少个users 是一个好的做法?
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-4 has-many-through counter-cache