4

尽管已经提出了类似的问题:

他们都没有真正解决我的问题。

我有三个模型,带有一个 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多少。userscalendar

我打算使用 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_calendarsusers表和表:count_of_users中的相应迁移calendars。)

但是后来,我在 Rails Guides 中偶然发现了这个警告

4.1.2.4:依赖

如果将 :dependent 选项设置为:

  • :destroy,当对象被销毁时,会在其关联对象上调用destroy。
  • :delete,当对象被销毁时,其所有关联对象将直接从数据库中删除,而不调用它们的destroy方法。

您不应在与其他类上的 has_many 关联连接的 belongs_to 关联上指定此选项。这样做会导致数据库中出现孤立记录。

因此,计算每个人有多少以及calendars每个人有多少是一个好的做法?useruserscalendar

4

1 回答 1

3

好吧,dependent: :destroy会破坏关联的记录,但不会更新counter_cache,所以你可能有错误的计数counter_cache。相反,您可以实现一个回调来销毁关联的记录,并更新您的counter_cache.

class Calendar < ActiveRecord::Base

  has_many :administrations
  has_many :users, through: :administrations


  before_destroy :delete_dependents

  private
  def delete_dependents
    user_ids = self.user_ids
    User.delete_all(:calendar_id => self.id)
    user_ids.each do |u_id|
      Calendar.reset_counters u_id, :users
    end
  end
end

同样,User也为模型实现这个

于 2015-08-28T17:15:52.097 回答