【问题标题】:Save a list of objects in a transaction operation在事务操作中保存对象列表
【发布时间】:2017-08-22 15:08:28
【问题描述】:

我正在尝试在我的 postgres 数据库中保存来自 excel 文件的对象列表。它必须在事务中完成。

从下面的代码中,我无法从无效案例回滚事务。一些无效案例之前的对象被保存,然后交易结束。

class UploadFile < ApplicationRecord
  # Others validations 

  def save_from_file
    # open file 
    Product.transaction do
      begin
        (2..file.last_row).each do |n|
          product = Product.new(id: file.cell(n,1), price: file.cell(n,2))
          product.save!
        end
      rescue ActiveRecord::RecordInvalid
        raise ActiveRecord::Rollback
      end
    end
  end

end

【问题讨论】:

    标签: ruby-on-rails transactions rails-postgresql


    【解决方案1】:

    不知道我是否完全理解您的问题,但您似乎想回滚整个事务。在这种情况下,你的问题就是救援。

    根据Active Record Transactions

    还要记住,事务块中抛出的异常将被传播(在触发 ROLLBACK 之后),因此您应该准备好在应用程序代码中捕获这些异常。

    一个异常是 ActiveRecord::Rollback 异常,它会在引发时触发 ROLLBACK,但不会被事务块重新引发。

    因此,如果您在救援中引发回滚,它不会触发事务块回滚,它只会回滚该特定对象。为了触发块回滚,它应该是这样的:

    Product.transaction do
      (2..file.last_row).each do |n|
        product = Product.new(id: file.cell(n,1), price: file.cell(n,2))
        product.save!
      end
    end
    

    这样,一旦 product.save,它会自动在整个块中引发回滚!引发错误。

    【讨论】:

      猜你喜欢
      • 2011-05-22
      • 2013-04-10
      • 2017-12-09
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-22
      • 1970-01-01
      相关资源
      最近更新 更多