LoginSignup
6
6

More than 5 years have passed since last update.

idのデフォルトをunsigned bigintに

Last updated at Posted at 2016-08-25

環境

Rails5.0 環境での話です。

idカラムはデフォでbigintにしたい

最初はmigrationのcreate_tableにオプションで渡して対応していました。

create_table :entries, id: :bigint, unsigned: true do |t|
end

こんな感じで書いてました。

レビューしていても抜け漏れは防げないのでinitializerでデフォルト値を上書きすることにしました。

もちろんbigintにする必要のないテーブルも多いのですが、そういうテーブルがbigintに変わったところでデメリットも少ないと判断しました。

idをbigintにする必要があるような大きなテーブル内に含まれる外部キーに使われるidに関してはintegerとbigintでテーブル容量に大きな差が出てきてしまう可能性等はあります。

そういう場合は明示的にid: :integer を指定することで防ぐことが可能です。

mysql_migration_ext.rb
ActiveSupport.on_load(:active_record) do
  require 'active_record/connection_adapters/mysql2_adapter'

  module ActiveRecord
    module ConnectionAdapters
      module MysqlMigrationExt
        def create_table(table_name, options = {})
          super(table_name, options.reverse_merge(id: :bigint, unsigned: true))
        end
      end

      class Mysql2Adapter
        include MysqlMigrationExt
      end
    end
  end
end

こんな感じです。

注意点

これは全てのテーブルのIDがunsigend bigintに既になっているもしくはmigration時に明示的にidの型を指定してあることが前提です。

なっていない場合初期値の上書きをおこなっているので、今後新たにmigrationした環境とその前からある環境でテーブルの状態に差異が発生します。

新たな環境でこれを導入した後に、rails db:migrate で新規にmigrationを行った後schema.rbに差異がでている場合は見なおしたほうが良いと思います。

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