2010-05-07 177 views
0

很抱歉的模糊標題之前引用,但我不知道怎麼問這樣的問題在同一行:)創建對象並保存對象DB

我對此再次嵌套項目嵌套itemgroups的訂單。用戶指定他想要在每個項目組中擁有的項目數量。我想在訂單本身創建時在訂單控制器的create方法中創建這些項目。

我在這裏有兩個問題。首先,我如何設置項目的引用,或者更好的是,將項目放入@order對象,以便在@order保存時保存它們?這些項目現在正在代碼中存儲在數據庫中,但未設置引用,因爲訂單沒有存儲在數據庫中,因此它還沒有一個id。

其次,即時通訊不知道如何使用正確的方式從我的項目組中獲取id。

@order = Order.new(params[:order]) 

@order.itemgroups.each do |f| 
    f.amount.times do 
    @item = Item.new() 
    @item.itemgroup_id = f.id 
    @item.save 
    end 
end 

回答

1

我必須在這裏做一些假設,因爲從您的描述來看,您的數據模型非常不尋常。特別是「Item」類似乎沒有任何用處。

我認爲它看起來像這樣:

class Order < ActiveRecord::Base 
    has_many :itemgroups 
end 

class Itemgroup < ActiveRecord::Base 
    belongs_to :order 
    has_many :items 
end 

class Item < ActiveRecord::Base 
    belongs_to :itemgroup 
end 

在這種情況下,可以使簡單的變化是你的循環改成這樣:

@order.itemgroups.each do |f| 
    f.amount.times do 
    item = itemgroup.items.build() #this links the fk before it exists 
    #this is where I assume you are doing something with the item 
    #otherwise the item class seems pointless 
    end 
end 
@order.save #saves dependent objects as well 
+0

我好像是我需要的東西。我會嘗試一下並回復你。你的假設是正確的,是的,在這種情況下,這些項目沒有任何用處,但我後來在系統中需要它們 – Flexo 2010-05-08 16:40:33

0

創建您訂購,但把整個東西變成了transaction。這種方式ActiveRecord會刪除訂單,如果它不能存儲的項目。

此外,除非項目不同(例如顏色,大小或其他),否則應該在其中存儲字段amount