ActiveRecord是否已将手动查询包装到事务中?

Hen*_*hiu 5 ruby activerecord ruby-on-rails

我有一个查询开始和结束这样的事务:

transaction = "BEGIN; UPDATE articles set x = 1 where id = 1; UPDATE articles set x = 2 where id = 2; END;"

ActiveRecord::Base.connection.execute(transaction)  
Run Code Online (Sandbox Code Playgroud)

我的问题:我甚至需要BEGIN和END吗?ActiveRecord是否已将我的查询包装到事务中?

ros*_*sta 6

ActiveRecord提供了在AR类和实例上都可用的事务方法,它将在给定块中包装查询.它甚至支持嵌套事务.

您可以将代码重写为:

sql = <<-SQL
UPDATE articles set x = 1 where id = 1; 
UPDATE articles set x = 2 where id = 2;
SQL

ActiveRecord::Base.transaction do
  ActiveRecord::Base.connection.execute(sql)
end
Run Code Online (Sandbox Code Playgroud)