LoginSignup
1
1

More than 5 years have passed since last update.

activerecord-mysql-unsignedを使う際の注意点

Last updated at Posted at 2015-09-19

MySQLで符号なしの整数を扱えるようにする activerecord-mysql-unsigned というgemがあるのですが、これを入れるとデフォルトで primary key を符号なしにしてしまうので、外部キー制約などをかけるときにしっかり参照する側も符号なしにするよう気をつけようという話。

あと、このgemの追加前にmigrationした人とgem追加後にmigrationした人ではschemaに差が出てしまうので、後から開発チームに加わった人が手元のPCなんかでmigrationするときも注意したほうがいいかと思います。

class CreateTables < ActiveRecord::Migration
  def self.up
    create_table :users do |t|
      t.string  :name, null: false
    end

    create_table :articles do |t|
      t.references :user, null: false, unsigned: true  #しっかりunsignedにする
    end

    add_index :articles, [:user_id]
    add_foreign_key :articles, :users  #でないとここで失敗する
  end

  def self.down
    drop_table :users
    drop_table :articles
  end
end
1
1
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
1
1