Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
191 views
in Technique[技术] by (71.8m points)

Rails HABTM - Properly removing an association

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_many relationship, so i have declared:

Product.rb

has_and_belongs_to_many :specials

Special.rb

has_and belongs_to_many :products

Now, with a product @product and a special @special, an association is created like so..

@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 @product is removed from specials, so @special.products.first==nil, however @product still contains @special, in other words @products.specials.first==@special

Is there any proper way, apart from writing a delete method, to do this in a single call?

question from:https://stackoverflow.com/questions/21278986/rails-habtm-properly-removing-an-association

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

collection.clear

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

In this example:

product = Product.find(x)

product.specials.clear

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

1.4m articles

1.4m replys

5 comments

57.0k users

...