LoginSignup
0
0

More than 5 years have passed since last update.

Rails foreign_keyに利用されているIDカラムを Int:11 から Bigint:20 に変更する

Last updated at Posted at 2019-02-07

個人的メモ

注意: データ量の大きいテーブルに対して無闇に行うとALTER TABLEが終わらず死ぬので注意

Rails 5.1 より前に作成されたテーブルはidinteger(INT:11)、5.1以降はbigint(BIGINT:20)に変更されており、これが混在しているとややこしいので統一したい。

さらに、該当のテーブルのIDを利用したforeign_key(FK制約)がある場合はそれを一度解除してから、カラムのタイプに変更を加え、再度foreign_key を設定してあげる必要がある。

なので、migrate ファイルは下記のようになる。

db/migrate/20190207040502_change_type_of_posts_id_from_integer_to_bigint.rb
class ChangeTypeOfPostsIdFromIntegerToBigint < ActiveRecord::Migration[5.2]
  def up
    remove_foreign_key :comments, column: :post_id
    change_column :posts, :id, :bigint, auto_increment: true
    change_column :comments, :post_id, :bigint
    add_foreign_key :comments, :posts, column: :post_id
  end

  def down
    remove_foreign_key :comments, column: :post_id
    change_column :comments, :post_id, :integer
    change_column :posts, :id, :integer, auto_increment: true
    add_foreign_key :comments, :posts, column: :post_id
  end
end
diff:db/schema.rb
   create_table "comments", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
-    t.integer "post_id"
+    t.bigint "post_id"

...

-  create_table "posts", id: :integer, options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|
+  create_table "posts", options: "ENGINE=InnoDB DEFAULT CHARSET=utf8", force: :cascade do |t|

schema.rbdiffの通り、create_table ~, id: :integerとあるテーブルはbigint化されていないテーブルなので、該当のテーブルを洗い出して、一気に変更をかけると良い。

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