Reputation: 26192
I have relations as follows :
Customer has many Orders
Order has many Parts
What I'm trying to do is to assign orders/parts to another customer, but I want to keep the original customer/orders/parts relation. So I tried this (assuming customer
is a Customer instance)
another_customer_id = 22
customer.orders.each do |order|
ord = order.dup
ord.customer_id = another_customer_id
ord.save!
order.parts.each do |part|
prt = part.dup
prt.order_id = ord.id
prt.save!
end
end
So I'm assuming once I do customer_two.orders
I will get everything as in first customer, but strangely I don't. It seems the first customer has double the orders/parts.
How can I do this in a better way?
update
When I use .dup
method the original customers orders are doubled in the database.
When I use .clone
instead of .dup
nothing happens, another customer still doesn't have orders from original customer
Upvotes: 0
Views: 107
Reputation: 956
The code you have here looks reasonable to me if you are using Rails >= 3.1. Before Rails 3.1 you need to use clone
instead of dup
. However, here is another method that you can try:
another_customer_id = 22
customer.orders.each do |order|
ord = Order.create(order.attributes.merge(:customer_id => another_customer_id))
order.parts.each do |part|
Part.create(part.attributes.merge(:order_id => ord.id))
end
end
Upvotes: 2