Rails ActiveRecord事务与类事务

时间:2017-05-29 17:13:05

标签: ruby-on-rails transactions

我对Rails Transaction类型有疑问。他们和每个人之间的差异是什么?

有效记录交易

ActiveRecord::Base.transaction do
    david.withdrawal(100)
    mary.deposit(100)
end

班级交易

Account.transaction do
    balance.save!
    account.save!
end

实例交易

account.transaction do
    balance.save!
    account.save!
end

非常感谢你!

1 个答案:

答案 0 :(得分:1)

AR交易是类交易

Account < ActiveRecord::Base
end

Account.transaction(block) == ActiveRecord::Base.transaction(block)

http://api.rubyonrails.org/classes/ActiveRecord/Transactions/ClassMethods.html https://apidock.com/rails/ActiveRecord/Transactions/ClassMethods/transaction

实例交易是一种便利方法

DB事务的实例方法是一种方便的方法,可以获得更多语法上更漂亮的代码。

你可以这样做。

account = Account.find(1)
ActiveRecord::Base.transaction do
  account.save!
end

对于上述任何一种情况都是一样的。无论哪种方式,它都会在事务中生成SQL代码。

证明在事务的实例方法的源代码中。

# File activerecord/lib/active_record/transactions.rb, line 276
def transaction(options = {}, &block)
  self.class.transaction(options, &block)
end

https://apidock.com/rails/v4.2.7/ActiveRecord/Transactions/transaction