我想知道它是否可以在rails中在一次交易中进行多次更新和创建。
我想创造一个号码。来自任何数组的Products
。但是对于每个产品,我还需要为其创建Company
和Category
。
所以这个想法是这样的
-- Start a transaction
//create a company
//create a category
while product_list
{
//create a product with company and category created above
}
-- end a transcation
因此,如果任何创建失败,我希望先前的更新/创建回滚。
答案 0 :(得分:15)
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