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

ruby-on-rails – Rails HABTM – 正确删除关联

发布时间:2020-12-16 22:03:17 所属栏目:百科 来源:网络整理
导读:我正在为购物网站开发创建特色的功能.一个产品可以有多个特殊的,显然一个特殊的可以有多个产品.. 我正在使用has_and_belongs_to_many关系,所以我已经声明: Product.rb has_and_belongs_to_many :specials Special.rb has_and belongs_to_many :products 现
我正在为购物网站开发创建特色的功能.一个产品可以有多个特殊的,显然一个特殊的可以有多个产品..

我正在使用has_and_belongs_to_many关系,所以我已经声明:

Product.rb

has_and_belongs_to_many :specials

Special.rb

has_and belongs_to_many :products

现在,通过产品@product和特殊的@special,会创建一个关联.

@special.products << @product

这样做之后,以下是事实:

@special.products.first == @product

重要的是:

@product.specials.first == @special

当我删除关联使用这个

@special.products.delete(@product)

那么@product从specials中删除,所以@ special.products.first == nil,然而@product仍然包含@special,换句话说@ products.specials.first == @ special

除了写一个删除方法之外,还有什么正确的方法,在一个通话中这样做?

解决方法

According to the Rails documentation:

collection.delete(object,…)

Removes one or more objects from the
collection by removing their associations from the join table. This
does not destroy the objects.

Brilliant reference here for you

我想你可以使用:

products = Product.find(x)
special = products.specials.find(y)

products.specials.delete(y)

这将为您尝试删除的对象创建ActiveRecord对象,这将为该功能提供清晰的定义

(编辑:李大同)

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

    推荐文章
      热点阅读