您可以使用
ActiveRecord::Base.connection.open_transactions
,看看你的方法是在一個事務中執行。
ActiveRecord::Base.connection.open_transactions == 0
暗示您的方法未在事務中執行。任何大於0的值都意味着你的方法在事務中執行。例如ActiveRecord::Base.connection.open_transactions > 0
更新:
從Rails文檔
all database statements in the nested transaction block become part of the parent transaction
如此開放交易的數量將是一個即使你是在一個嵌套事務。
這是我在我的控制檯
ActiveRecord::Base.transaction do
User.first.update_attribute(:first_name, "something")
ActiveRecord::Base.transaction do
User.first.update_attribute(:last_name, "something")
p ActiveRecord::Base.connection.open_transactions
end
end
(0.3ms) BEGIN
User Load (0.8ms) SELECT "users".* FROM "users" LIMIT 1
(0.8ms) UPDATE "users" SET "first_name" = 'something', "updated_at" = '2013-11-20 18:33:52.254088' WHERE "users"."id" = 1
User Load (0.5ms) SELECT "users".* FROM "users" LIMIT 1
(0.4ms) UPDATE "users" SET "last_name" = 'something', "updated_at" = '2013-11-20 18:33:52.266976' WHERE "users"."id" = 1
1
(14.2ms) COMMIT
=> 1
了,如果你的代碼在'config.use_transactional_fixtures = TRUE'測試運行,那麼你是一個交易更深? C-; – Phlip
@Phlip:我希望我的更新能夠回答你的問題 – usha