Create and update multiple models in a single transaction

I wanted to know if it is possible to make several updates and creations in rails within a single transaction.

I wanted to create no. from Productsfrom any array. But for every product I also need to create Companyand Categoryfor him.

So the idea is 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 creations fails, I want the previous updates / creations to be rolled back.

+5
source share
1 answer
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
+11
source

All Articles