Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Multiple models creation and updation under one transaction

I wanted to know if its possible in rails to do multiple updates and creations under one transaction.

I wanted to create a no. of Products from any array. But for each product i also need to create Company and Category for it.

So the idea is like this

-- Start a transaction
//create a company
//create a category
while product_list
{
   //create a product with company and category created above
}
-- end a transcation

So if any of the creation fails i want the earlier updation/creations to rollback.

like image 208
Fraz Anjum Avatar asked Jul 29 '11 00:07

Fraz Anjum


1 Answers

begin
  ActiveRecord::Base.transaction do
    # create a company
    # create a category
    while product_list
    {
      # create a product with company and category created above
    }
  end
rescue => e
  # something went wrong, transaction rolled back
end
like image 64
Björn Nilsson Avatar answered Nov 15 '22 22:11

Björn Nilsson