2010-05-07 184 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