Ruby on Rails在新线程上回滚

时间:2018-01-03 14:50:20

标签: ruby-on-rails ruby

我遇到了以下代码的问题。出于某种原因,它不允许我在回滚方法后修改进度条的状态。它根本不会做任何事情。我不明白为什么。我不能打电话给失败!方法在操作方法中,因为它将回滚并更改进度条的状态。

class Importer
  attr_accessor :file

  def initialize(file)
   @file = file
   @pb = ProgressBar.create
   @pb.number_of_rows(file)
  end

  def import(user)
    Thread.new do
      ActiveRecord::Base.transaction do
        errs = operation(user)
        Rails.logger.info "HELLO"
        if errs.any?
          raise ActiveRecord::Rollback
          @pb.failed!
        end
      end
      Rails.logger.info "WORLD"
    end
  end

  def operation(user)
    errs = []
    i = 0
    user.insurances.each do |insurance|
      i = i+1
      if insurance.can_have_plan?
        Plan.create(:insurance => insurance)
        @pb.update_attribute(:current_row, i )
      else
        errs << "#{insurance.id} cant have a plan"
      end
    end
    errs
  end
end

当我删除加注时,它将按预期工作。另外,为什么它不打印HELLO但它只打印WORLD?

1 个答案:

答案 0 :(得分:0)

尝试这样的事情。在您的代码中,@ fb.failed也会因基本事务而被回滚。

您的代码应如下所示。

def import(user)
    pb_failure = false
    Thread.new do
      ActiveRecord::Base.transaction do
        errs = operation(user)
        Rails.logger.info "HELLO"
        if errs.any?
          pb_failure = true
          raise ActiveRecord::Rollback
        end
      end
      @pb.failed! if pb_failure
      Rails.logger.info "WORLD"
    end
  end