尽管已经提出了类似的问题:
他们都没有真正解决我的问题。
我有三个模型,带有一个 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
连接管理模型具有以下属性:
id
user_id
calendar_id
role
我想计算每个有多少calendars
,每个有user
多少。users
calendar
我打算使用 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
。)
但是后来,我在 Rails Guides 中偶然发现了这个警告:
4.1.2.4:依赖
如果将 :dependent 选项设置为:
- :destroy,当对象被销毁时,会在其关联对象上调用destroy。
- :delete,当对象被销毁时,其所有关联对象将直接从数据库中删除,而不调用它们的destroy方法。
您不应在与其他类上的 has_many 关联连接的 belongs_to 关联上指定此选项。这样做会导致数据库中出现孤立记录。
因此,计算每个人有多少以及calendars
每个人有多少是一个好的做法?user
users
calendar