简体   繁体   English

Ruby on Rails在新线程上回滚

[英]Ruby on Rails Rollback on a new thread

I am running into an issue with the following code. 我遇到了以下代码的问题。 For some reason, it will not allow me to modify the state of my progress bar after the rollback method. 由于某些原因,它不允许我使用回滚方法修改进度条的状态。 It will simply not do anything. 它根本不会做任何事情。 I don't see why. 我不明白为什么。 And I can't call failed! 我不能打电话失败! method within the operation method because it will rollback and change the state of my progress bar. 操作方法中的方法 ,因为它会回滚和改变我的进度条的状态。

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

When I delete raise, it will work as desired. 当我删除加薪时,它将按需要工作。 Also, why it doesn't print HELLO but it only prints WORLD? 另外,为什么它不打印HELLO但只打印WORLD?

Try something like this. 尝试这样的事情。 in your code @fb.failed also gets rolled back due to base transaction. 代码中的@ fb.failed也由于基本事务而回滚。

Your code should look like this. 您的代码应如下所示。

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM