产品(如iPod Classic) :has_many => :listing,:dependent => :破坏
列表(例如“我的名字是乔,我有一个待售的iPod) :belongs_to => :产品
因此,如果删除给定的产品,则指向该产品的所有商品都会被删除。这是有道理的,并且是设计的。
但是,我正在编写一个“合并”功能,您将两个产品合并为一个,并合并其列表。所以,假设我的两款产品是“iPod Color”和“iPod Classic”,我想合并两者。我想要做的是说,“iPod Color,合并到iPod Classic”,结果应该是:
嗯,这应该都可以,但不删除任何列表。然而,我有这个控制器,无论出于什么原因我销毁“iPod Color”产品,即使确认列表已被移动到“iPod Classic”并保存到数据库,之前指向的列表“iPod Color”也被破坏了,我无法弄明白为什么。就好像他们保留了与被破坏产品的某种联系,因此开始自我毁灭。
我遗失了多么痛苦的事情?
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
答案 0 :(得分:4)
我看到了相同的行为并重新加载解决了它。
def merge
merging_from = Product.find(params[:id])
merging_to = Product.find_by_model(params[:merging_to])
if merging_from && merging_to && merging_from != merging_to
merging_to.listings << merging_from.listings
merging_from.reload.destroy
end
end