在一个事务下创建和更新多个模型

Fra*_*jum 6 ruby transactions ruby-on-rails

我想知道它是否可以在rails中在一次交易中进行多次更新和创建.

我想创造一个号码.的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
Run Code Online (Sandbox Code Playgroud)

因此,如果任何创建失败,我希望先前的更新/创建回滚.

Bjö*_*son 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
Run Code Online (Sandbox Code Playgroud)

  • 在事务中引发 ActiveRecord::Rollback 将导致回滚。(此异常不会传播到事务块之外,因此您无需捕获它) (2认同)