MySQL + ActiveRecord でシーケンス番号を生成。

MySQLActiveRecordでsequenceみたいなことをする方法。

LAST_INSERT_ID()を使う。ここらへんを参考に。

モデルを生成。

$ ./script/generate model xxx_sequence

migration

class XxxSequences < ActiveRecord::Migration
  def self.up
    create_table :xxx_sequences do |t|
    end
    execute "INSERT INTO xxx_sequences VALUES(10000)" # 初期値を設定
  end

  def self.down
    drop_table :xxx_sequences
  end
end

migration実行。

$ rake db:migrate

model

class XxxSequence < ActiveRecord::Base
  def self.next_id
    update_all("id=LAST_INSERT_ID(id+1)")
    return find_by_sql("SELECT LAST_INSERT_ID() AS id")[0].id
  end
end

LAST_INSERT_ID(expr)がid+1の値を記憶、LAST_INSERT_ID()が呼ばれたときに記憶した値を返す。

consoleで確認。

$ ./script/console

>> XxxSequence.next_id
=> 10001
>> XxxSequence.next_id
=> 10002