ActiveRecord已经将手动查询打包到事务中了吗?

时间:2022-04-07 23:40:04

I have a query that begins and ends a transaction like this:

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

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

ActiveRecord::Base.connection.execute(transaction)  

My question: Do I even need the BEGIN and END? Does ActiveRecord already wrap my query into a transaction?

我的问题是:我是否需要开始和结束?ActiveRecord已经将我的查询封装到事务中了吗?

1 个解决方案

#1


4  

ActiveRecord provides the transaction method, available on both AR classes and instances, that will wrap queries within a given block. It even supports nested transactions.

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

You could rewrite your code as:

您可以将代码重写为:

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

#1


4  

ActiveRecord provides the transaction method, available on both AR classes and instances, that will wrap queries within a given block. It even supports nested transactions.

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

You could rewrite your code as:

您可以将代码重写为:

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