views:

37

answers:

2

Sorry about the vague title, but i didnt know how to ask the question in one line :)

I have an order with nested itemgroups that again have nested items. the user specify the amount of item that he would like to have in each itemgroup. I would like to create these items in the create method of the orders controller when the order itself is being created.

I kinda have 2 problems here. First, how do i set the reference of the items, or better yet, put the items into the @order object so they are saved when the @order is saved? the items are being stored in the db as the code is now, but the reference is not set because the order is not stored in the db yet so it doesnt have an id yet.

Second, im not sure im using the correct way to get the id from my itemgroup.

@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  A: 

I have to make a few assumptions here, because from your description, your data model is quite unusual. In particular the "Item" class seems to serve no purpose.

I assume it looks like this:

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

In which case, the simplest change you can make is to change your loop to this:

 @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
MattMcKnight
I seems like the thing i need. i will try it out and get back to you. your assumptions is correct, and yes in this case the items serve no purpose, but i need them later on in the system
Flexo
A: 

Create you order but put the whole thing into a transaction. That way ActiveRecord would removed the order if it can't store on of the items.

Also, unless the items differ (e.g. in color, size or whatever) you should store a field amount with them.

Thomas R. Koll