2011-07-29 55 views
5

我想知道它是否可能在rails中執行一次事務下的多個更新和創建。在一次交易下創建和更新多個模型

我想創建一個no。來自任何陣列的Products。但對於每個產品,我還需要爲其創建CompanyCategory

這樣的想法是這樣的

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

因此,如果任何創作的失敗,我想前面的更新用/創作回滾。

回答

10
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 
+0

感謝這就是我一直在尋找的...... –

+1

順便說一句,我們用什麼命令回滾事務? –

+1

在事務中引發ActiveRecord :: Rollback會導致回滾。 (這個異常不會傳播到事務塊之外,所以你不需要捕獲它) –