2011-01-08 80 views
1

產品(像iPod經典) :的has_many =>:列表,:依賴=>:摧毀當摧毀一個記錄,另外一個被摧毀

信息(如「我的名字是喬,我有一個iPod的銷售) :belongs_to的=>:產品

所以,如果我刪除一個給定的產品,所有指向它的上市被刪除是有道理的,並且是由設計

不過,我。我正在寫一個「合併」功能,在這裏你將兩個產品合併爲一個產品,併合並他們的產品。所以,假設我的兩款產品是「iPod Co lor「和」iPod Classic「,我想合併這兩者。我想要做的是說,「iPod的顏色,合併到iPod的經典」,而結果應該是:

  1. 所有iPod的顏色房源被重新指向iPod經典產品
  2. 的PRODUCT_ID後變化,上市(S)保存
  3. 我然後刪除「iPod的色彩」產品

好了,應該都做工精細,但不刪除任何信息。然而,我有這個控制器,並且無論什麼原因,當我銷燬「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 

回答

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 
+0

天才。那樣做了! – jefflunt 2011-01-08 21:07:48