0
0

More than 1 year has passed since last update.

#Rails の controller で処理の多重送信を防ぐために、model に 処理のid単位の履歴テーブルを作成して、transaction lock と rollback を利用する例

Last updated at Posted at 2019-12-23

処理一個はユニークな proceeding_id を持つものとする
重複処理が起こった場合はレコードがINSERTできずにbad request を返す
処理本体が失敗した場合はrollbackされて再度処理可能状態となる

class SomeController
  def create
    ProceedingHistory.transaction do
      begin
        ProceedingHistory.create(proceeding_id: proceeding_id)
      rescue ActiveRecord::RecordNotUnique
        head :bad_request
        return
      end

      do_something
    end

    head :ok
  end
end

# == Schema Information
#
# Table name: proceeding_histories
#
#  id              :bigint           not null, primary key
#  created_at      :datetime
#  proceeding_history_id :string(255)
#
# Indexes
#
#  index_proceeding_histories_on_proceeding_history_id  (proceeding_history_id) UNIQUE
#

class ProceedingHistory < ApplicationRecord
end

Original by Github issue

チャットメンバー募集

何か質問、悩み事、相談などあればLINEオープンチャットもご利用ください。

Twitter

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