pramodh
pramodh

Reputation: 1329

Merging 2 ActiveRecords of same type into one

I have an active record association below

class Order < ActiveRecord::Base
  has_many :lineitems, dependent: :destroy
end

class Lineitem < ActiveRecord::Base
  belongs_to :order
end

I have 2 Orders with different line items.

I want to merge these 2 orders to a new order and then delete the previous 2 records.

Is there an easy way to accomplish this, without creating new lineitems?

What I want is the same lineitems pointing to the new Order. Instead of making new copies.

Upvotes: 1

Views: 37

Answers (2)

SunnyMagadan
SunnyMagadan

Reputation: 1859

You can do it by this way:

  1. Create new order

    new_order=Order.create #Pass additional parameters to create method if needed

  2. Take all LineItem which is belongs to other two orders. E.g. orders with ids 1 and 2. And attach all LineItems to new_order:

    LineItem.where(order_id: [1, 2]).update_all(order_id: new_order.id)

  3. Delete old orders

    Order.where(id: [1, 2]).destroy_all

Upvotes: 2

nickcen
nickcen

Reputation: 1692

o1 = Order.find(1)
o2 = Order.find(2)

# create new one, and assign lineitems to the new order

o3 = Order.create(...)
o3.lineitems = o1.lineitems + o2.lineitems

# destroy the old order
o1.destroy
o2.destroy

Upvotes: 0

Related Questions