我有一个查询开始和结束这样的交易:
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是否已将我的查询包装到事务中?
答案 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