2017-03-23 30 views
0

我有一個問題,試圖克隆具有嵌套元素的對象。我知道如何完全克隆它,但我想克隆每個嵌套級別上的一些子元素。Ruby on rails克隆/重複與篩選嵌套元素

所以可以說我有結構像這樣,通過實例名稱即時決策(它不是實際情況)

class Town < ActiveRecord::Base 
has_many :districts 
has_many :buildings, through: :districts 

class District < ActiveRecord::Base 
belongs_to :town 
has_many :buildings 

class Building < ActiveRecord::Base 
belongs_to :district 
has_many :rooms 
has_many :toilets 

#and i have of course rooms and toilets with belongs_to relation to Building 

所以basicaly,如果我想克隆整個現有城區對象我只想做一些像

Town.last.clone 

但我想這樣做,而不是。我想複製現有的城鎮,然後根據我的收藏重新創建僅一些兒童物品。因此,如果城鎮有10個地區,我想只複製其中的一個,或者更多(基於我的收藏),然後地區有100個房屋,我將再次僅複製我需要的房間,直到房間和洗手間。所以我嘗試了這樣的事情。

#now i have these collections, i get them in some fashion, and they belong to Town(1) below  
districts = District.find(1,2,3) #those ids are belonging to Town 
buildings = Building.find(1,2,3) #those ids are belonging to districts above 
rooms = Room.find(1,2,3,4,5,6) # and are belonging to some of buildings above 
toilets = Toilet.find(1,2,3,4,5,6,7) #and are belonging to some of buildings 

#so now i want to do this 
old_town = Town.find(1) 
new_town = old_town.dup.tap 

districts.each od |district| 
    new_town.districts << district.dup 
end 
#and i get all the districts to new created town but when i try further in nesting it wont work, like this 

districts.each od |district| 
    new_town.districts << district.dup 

    buildings.each do |building| 
    district.buildings << building.dup 
    end 
end 

#and so on inside it for toilets and rooms it just wont work, like it doesnt attach them to new_town. What am i doing wrong? 

所以我只是想選擇性的dup /克隆過濾元素屬於父母。彼此尊重他們的關係。

謝謝分配。

+0

您是否想將建築物的重複項目放入屬於新城鎮的區域?如果是這樣的話:'district.buildings << building.dup'應該改變,所以'#buildings'的接收者是重複的區域。 Btw。這些:: find方法真的很混亂。 – DiodonHystrix

+0

嗨,是的,我正在嘗試添加建築物重複項,以便將它附加到我創建的區域重複項。我怎麼能做到這一點?現在我有點困惑,我知道你在說什麼,但不知道如何在同一個循環中實現這一點。而對於廁所和房間,我以同樣的方式做對吧? – Tester

回答

0
districts.each do |district| 
    district_dup = district.dup 
    buildings.each do |building| 
    district_dup.buildings << building.dup 
    end 
    new_town.districts << district_dup 
end 

你可以試試類似的東西嗎?如果您想添加房間和廁所,則需要創建building_dup,就像district_dup一樣。

編輯:清潔版本

districts.map(&:dup).each do |dis| #creates an Array of duplications and iterates through elements 
    dis.buildings = buildings.map(&:dup).each do |building| #creates an Array of duplications which is later added to dis.buildings 
    building.rooms = rooms.map(&:dup) 
    building.toilets = toilet.map(&:dup) 
    end 
end 

如果dis.buildings = buildings.map(&:dup).each失敗,請嘗試在所有的情況下改變#=#concat

+0

我明天嘗試,但我認爲這是問題。你有這個觀點。我很愚蠢 - - 我想知道爲什麼它不附加他們...我把它標記爲正確的答案,因爲它是99% – Tester