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

时间:2013-04-23 01:24:02

标签: ruby-on-rails ruby activerecord

我有一个查询开始和结束这样的交易:

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

ActiveRecord::Base.connection.execute(transaction)  

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

1 个答案:

答案 0 :(得分:5)

ActiveRecord provides the transaction method,在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