11
7

More than 5 years have passed since last update.

ActiveRecord::Base.transactionブロックが正常終了する例外としない例外

Last updated at Posted at 2016-06-15

ActiveRecord::Rollbackは正常終了するので後に書いた処理が走る


def execute
  result = false
  ActiveRecord::Base.transaction do
    # なんか処理
    raise ActiveRecord::Rollback # <= ここで例外(ActiveRecord::Rollback)は

    # いろいろ処理
    result = true
  end
  result # <= ここ通る
end

ActiveRecord::Rollback以外は正常終了しないので後に書いた処理は走らず、該当rescueまで飛ぶ


def execute
  result = false
  ActiveRecord::Base.transaction do
    # なんか処理
    hoge.save!  # <= ここで例外(ActiveRecord::RecordInvalid)は

    foo.bar() # <= ここで例外(Custom::Error)も

    # いろいろ処理
    result = true
  end
  result # <= ここ通らない
rescue Custom::Error, ActiveRecord::RecordInvalid
  # 例外対応
end
11
7
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
7