When destroying one record, another one gets destroyed
Posted
by
normalocity
on Stack Overflow
See other posts from Stack Overflow
or by normalocity
Published on 2011-01-08T19:54:12Z
Indexed on
2011/01/08
20:53 UTC
Read the original article
Hit count: 205
Products (like an iPod Classic) :has_many => :listings, :dependent => :destroy
Listings (like "My name is Joe, and I have an iPod for sale) :belongs_to => :product
So, if I delete a given Product, all the listings that point to it get deleted. That makes sense, and is by design.
However, I am writing a "merge" function, where you merge two Products into one, and combine their Listings. So, let's say my two products are "iPod Color" and "iPod Classic", and I want to merge the two. What I want to do is say, "iPod Color, merge into iPod Classic", and result should be that:
- All the iPod Color Listings are re-pointed to the iPod Classic product
- After the product_id change, the Listing(s) are saved
- I then delete the "iPod Color" product
Well, that should all work fine, without deleting any Listings. However, I've got this controller, and for whatever reason when I destroy the "iPod Color" Product, even after confirming that the Listings have been moved to "iPod Classic" and saved to the database, the Listings that were previously pointed to "iPod Color" get destroyed as well, and I can't figure out why. It's as if they are retaining some kind of link to the destroyed product, and therefore begin destroyed themselves.
What painfully obvious thing am I missing?
def merge
merging_from = Product.find(params[:id])
merging_to = Product.find_by_model(params[:merging_to])
unless merging_to.nil?
unless merging_from.nil?
unless merging_from == merging_to # you don't want to merge something with itself
merging_from.listings.each do |l|
l.product = merging_to
l.save
end
# through some debugging, I've confirmed that my missing Listings are disappearing as a result of the following destroy call
merging_from.destroy
end
end
end
© Stack Overflow or respective owner