无法通过关联销毁具有 has_many 的模型

Cannot destroy a model with a has_many through assocation

我通过 has_many :through 关联链接了以下模型。以下是以下型号

class Campaign
  has_many :email_notification_code_percentages, dependent: :destroy
  has_many :email_notification_code_percentage_trackers, through: :email_notification_code_percentages
end

class EmailNotificationCodePercentage < ApplicationRecord
  belongs_to :campaign
  has_many :email_notification_code_percentage_trackers, dependent: :destroy
end

class EmailNotificationCodePercentageTracker < ApplicationRecord
  belongs_to :email_notification_code_percentage
end


当我尝试执行以下命令时 @campaign.email_notification_code_percentage_trackers.destroy_all 我收到以下错误:

Cannot modify association 'Campaign#email_notification_code_percentage_trackers' because the source reflection class 'EmailNotificationCodePercentageTracker' is associated to 'EmailNotificationCodePercentage' via :has_many. (ActiveRecord::HasManyThroughCantAssociateThroughHasOneOrManyReflection)

这里有什么问题?这应该是一个简单的 has many through association,如通过 rails 示例定义的那样。我在这里错过了什么?这对我来说是正确的。

这是预期的行为,您可以在 API 文档 (https://api.rubyonrails.org/classes/ActiveRecord/Associations/ClassMethods.html) 中阅读:

An important caveat with going through has_one or has_many associations on the join model is that these associations are read-only.

:through 选项或通过 has_and_belongs_to_many 宏定义的关联有点特殊。

因此,有几种替代方法:

  1. 迭代每个元素:
# be careful if the association is very large, you can run into some memory or timeout issues
@campaign.email_notification_code_percentage_trackers.each(&:destroy)
  1. 使查询有点不同,以便能够使用 destroy_all:
EmailNotificationCodePercentage.merge(@campaign.email_notification_code_percentage_trackers).destroy_all