LoginSignup
3
0

More than 5 years have passed since last update.

rails migration 生SQL トランザクション

Last updated at Posted at 2017-12-23

migration時に生SQLを使ってかつトランザクションを設定したい時の書き方

エラー時にrescueでcatchし、ロールバックするようにする。
migrationでエラーしたことがわかるようにrescueでキャッチした後、raiseを実行している。

# sqlAまたはsqlBでエラーした場合、ロールバックされる。両方とも成功した場合にcommitする。

class ChangeTests < ActiveRecord::Migration
  def up
    begin
      ActiveRecord::Base.connection.execute("start transaction") 

      sqlA = "update tests set price = 1000 where status = 1;"
      ActiveRecord::Base.connection.execute(sqlA)

      sqlB = "update tests set price = 2000 where status = 2;"
      ActiveRecord::Base.connection.execute(sqlB)

      ActiveRecord::Base.connection.execute("commit") 
    rescue
      ActiveRecord::Base.connection.execute("rollback")
      raise "エラーが発生したのでロールバックしました"
    end
  end
end

3
0
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
3
0