Mar*_*ins 31 ruby-on-rails has-and-belongs-to-many ruby-on-rails-3
我正在开发一个用于为购物网站创建特价的功能.一种产品可以有多种特殊产品,显然特殊产品可以有多种产品.
我正在使用一段has_and_belongs_to_many
关系,所以我宣布:
Product.rb
has_and_belongs_to_many :specials
Run Code Online (Sandbox Code Playgroud)
Special.rb
has_and belongs_to_many :products
Run Code Online (Sandbox Code Playgroud)
现在,通过产品@product
和特殊产品,@special
可以创建一个类似的关联.
@special.products << @product
Run Code Online (Sandbox Code Playgroud)
执行此操作后,以下情况属实:
@special.products.first == @product
Run Code Online (Sandbox Code Playgroud)
而且,重要的是:
@product.specials.first == @special
Run Code Online (Sandbox Code Playgroud)
当我删除使用此关联
@special.products.delete(@product)
Run Code Online (Sandbox Code Playgroud)
然后@product
从特价中删除,换句话说@special.products.first==nil
,@product
仍然包含 @special
@products.specials.first==@special
除了编写删除方法之外,还有什么方法可以在一次调用中执行此操作吗?
Ric*_*eck 60
collection.delete(object,...)
通过从连接表中删除它们的关联,从集合中删除一个或多个对象.这不会破坏对象.
您可以使用:
product = Product.find(x)
special = product.specials.find(y)
product.specials.delete(special)
Run Code Online (Sandbox Code Playgroud)
这会为您要删除的对象创建ActiveRecord对象,从而为函数提供清晰的定义
collection.clear
通过从连接表中删除它们的关联来从集合中删除所有对象.这不会破坏对象.
在这个例子中:
product = Product.find(x)
product.specials.clear
Run Code Online (Sandbox Code Playgroud)