読者です 読者をやめる 読者になる 読者になる

技術のメモ帳

気が向いたときに書いてます

ActiveRecord::Base.transactionの使い方を誤解していた

  • (誤解)テーブル名が異なる場合、 ActiveRecord::Base から実行しないとNG!?
  • (正解)同じクラスからコールされるので、Baseのサブクラスならば Model.transaction でも model_instance.transaction でもOK
# == Different Active Record classes in a single transaction
#
# Though the #transaction class method is called on some Active Record class,
# the objects within the transaction block need not all be instances of
# that class. This is because transactions are per-database connection, not
# per-model.
#
# In this example a +balance+ record is transactionally saved even
# though #transaction is called on the +Account+ class:
#
#   Account.transaction do
#     balance.save!
#     account.save!
#   end
#
# The #transaction method is also available as a model instance method.
# For example, you can also do this:
#
#   balance.transaction do
#     balance.save!
#     account.save!
#   end

ちゃんとコード読もうぜ、という話だった。

参考

github.com