Rails即使事务回滚,也会在事务中保存记录?

Tom*_*son 2 transactions ruby-on-rails-3

我有一系列记录作为交易的一部分保存.除了正常的AR记录,我正在进行信用卡网关交易.如果它或AR事务失败,我希望所有内容都回滚...除了从信用卡网关返回的失败事务(原因,日期等)的数据.就像是

def pay
  Payment.transaction do
    payment.save
    other.save
    result = credit_card.purchase  # this does the gateway transaction, no database stuff
    if result.failure
      raise ActiveRecord::Rollback
      result.save  # this is the part I want to always save
    end
    another.save
  end
end
Run Code Online (Sandbox Code Playgroud)

有没有办法将事务中的特定部分排除在故障后回滚?

Rails 3.2.5,MySQL 5.1

Fre*_*ung 8

我不是100%确定我理解你为什么要这样做,但你可以在交易之外保存信用卡的东西吗?

result = nil
Payment.transaction do
  payment.save
  other.save
  result = credit_card.purchase  # this does the gateway transaction, no database stuff
  if result.failure
    raise ActiveRecord::Rollback      
  end
end
result.save
Run Code Online (Sandbox Code Playgroud)

(由于块变量作用域的工作原理,您需要在事务之前将结果设置为nil)

另一种可能的策略是使用事务是基于每个连接完成的事实.两个线程将使用不同的连接,所以你可以这样做

Payment.transaction do
  payment.save
  other.save
  result = Thread.new do
    ActiveRecord::Base.connection_pool.with_connection do
      credit_card.purchase
    end
  end.value
  if result.failure 
    raise ActiveRecord::Rollback
  end
end
Run Code Online (Sandbox Code Playgroud)

这里购买发生在另一个线程上,即具有自己的数据库连接.该线程中发生的任何事情都不会被回滚