为什么集合= has_many上的对象:通过删除关联时连接模型上的触发器回调?

Bre*_*uir 5 activerecord ruby-on-rails callback has-many-through ruby-on-rails-4

Rails 4文档说明了关于has_many :through关系的连接模型上的销毁回调:

collection=objects通过适当删除和添加对象来替换集合内容.如果:through选项为true,则会触发连接模型中的回调,但销毁回调除外,因为删除是直接的.

值得庆幸的是,它至少有记载,但我想知道为什么到底是这样的?希望有一个技术原因,否则它只是疯了!

在我的情况下,我has_and_belongs_to_many在连接表模型上有一个关系到另一个模型.删除第一个连接表上的关联记录时,永远不会删除该第二个连接表上的记录.我使用了这种感觉很难的东西,我必须在:through关系的每一方面重复自己:

has_many :schools_templates, dependent: :destroy
has_many :templates, through: :schools_templates, before_remove: :remove_groups_school_templates

private

def remove_groups_school_templates(template)
  schools_templates.where(template: template).first.groups.clear
end
Run Code Online (Sandbox Code Playgroud)

对两个外键之间的连接表记录进行"确保"唯一性验证,这就是我可以调用first回调的原因.

小智 1

所以前几天我遇到了同样的问题。就我而言,我所做的事情与您所做的类似,并且遇到了相同的问题,连接表被删除而不是被销毁。

我开始查看代码,我相信文档已经过时了。 has_many_through_association

您需要做的就是将 dependent: :destroy 添加到 has_many :through 关系中。

class User
  has_many :partnerships, dependent: :destroy
  has_many :partners, through: :partnerships, dependent: :destroy
end
Run Code Online (Sandbox Code Playgroud)

我所面对的痛苦是:

user.partner_ids = [1,2,3]
#creates the relationships
user.partner_ids = []
#was deleting the records from partnerships without callbacks.
Run Code Online (Sandbox Code Playgroud)

依赖于: :destroy 的伙伴关系修复了这个问题。现在正在运行回调,一切又恢复正常了。