加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – 为什么集合= has_many上的对象:通过删除关联

发布时间:2020-12-16 21:06:01 所属栏目:百科 来源:网络整理
导读:Rails 4文档说明了关于has_many:through关系的连接模型上的destroy回调: collection=objects Replaces the collections content by deleting and adding objects as appropriate. If the :through option is true callbacks in the join models are trigge
Rails 4文档说明了关于has_many:through关系的连接模型上的destroy回调:

collection=objects Replaces the collections content by deleting and
adding objects as appropriate. If the :through option is true
callbacks in the join models are triggered except destroy callbacks,
since deletion is direct.

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

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

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

在两个外键之间的连接表记录中有一个’确保’唯一性的验证,这就是我可以在回调中首先调用的原因.

解决方法

所以前几天我遇到了同样的问题.
在我的情况下,我做了类似于你正在做的事情,并遇到了同样的问题,连接表被删除而不是被销毁.

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

您需要做的就是将依赖::: destroy添加到has_many:through关系中.

class User
  has_many :partnerships,dependent: :destroy
  has_many :partners,through: :partnerships,dependent: :destroy
end

我正在处理的痛苦是:

user.partner_ids = [1,2,3]
#creates the relationships
user.partner_ids = []
#was deleting the records from partnerships without callbacks.

依赖::破坏合作伙伴关系固定的那个.回调现在正在运行,事情又好了.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读