Ruby-on-rails Rails HABTM - 正确删除关联
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21278986/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Rails HABTM - Properly removing an association
提问by Marco Prins
I am developing a feature for creating specials, for a shopping website. One product can have more than one special, and obviously a special can have more than one product..
我正在开发一个功能,用于创建一个购物网站的特价商品。一个产品可以有多个特价,显然一个特价可以有多个产品。
I am using a has_and_belongs_to_manyrelationship, so i have declared:
我正在使用has_and_belongs_to_many关系,所以我声明:
Product.rb
产品.rb
has_and_belongs_to_many :specials
Special.rb
特殊.rb
has_and belongs_to_many :products
Now, with a product @productand a special @special, an association is created like so..
现在,有了一个产品@product和一个特殊的@special,一个关联就这样创建了..
@special.products << @product
After doing this, the following is true:
执行此操作后,以下情况为真:
@special.products.first == @product
and, importantly:
而且,重要的是:
@product.specials.first == @special
When i delete the association using this
当我使用这个删除关联时
@special.products.delete(@product)
then @productis removed from specials, so @special.products.first==nil, however @productstill contains@special, in other words @products.specials.first==@special
then@product已从特价商品中删除,因此@special.products.first==nil,但是@product仍然包含@special,换句话说@products.specials.first==@special
Is there any proper way, apart from writing a delete method, to do this in a single call?
除了编写删除方法之外,是否有任何正确的方法可以在一次调用中执行此操作?
回答by Richard Peck
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
You can use:
您可以使用:
product = Product.find(x)
special = product.specials.find(y)
product.specials.delete(special)
This creates ActiveRecord objects for both the object you're trying to remove, which gives clear definition to the function
这会为您尝试删除的对象创建 ActiveRecord 对象,从而为函数提供清晰的定义
collection.clear
Removes all objects from the collection by removing their associations from the join table. This does not destroy the objects.
收藏.clear
通过从连接表中删除它们的关联,从集合中删除所有对象。这不会破坏对象。
In this example:
在这个例子中:
product = Product.find(x)
product.specials.clear

