LoginSignup
43
34

More than 5 years have passed since last update.

Rails5.1に移行後のmigrationファイルの注意

Last updated at Posted at 2017-07-28

Rails5.1後に作成するmigrationファイルはデフォルトでidカラムにbigint型を使う(Mysqlの場合)
規模が大きいアプリケーションなら良いが、これによって不都合が出る人も割りといるのではないか。

そもそもintで十分なところをbigintにすると、1レコード辺りのデータ容量を余計に使ってしまう。

解決するには、create_tableメソッドのオプションでidの型を指定する。

create_table :cards_tags, id: :integer do |t|
# ...
end

bigintによって既存テーブルとの関係でエラーの原因になることも。以下で詳しく述べる。

referencesのエラー

例えば、既存テーブルを参照するmigrationファイルを生成して実行してみると、以下エラーになることがある。

以下のように既存のcardsとtagsを紐付ける中間テーブルを作成

cards_tagsの生成
class CreateCardsTags < ActiveRecord::Migration[5.1]
  def change
    create_table :cards_tags do |t|
      t.references :card, foreign_key: true
      t.references :tag, foreign_key: true

      t.timestamps
    end
  end
end

実行後、

Mysql2::Error: Table 'copylog_development.cards_tags' doesn't exist: SHOW FULL FIELDS FROM cards_tags

とでる。

referencesで作ろうとしているcard_id, tag_idはbigint型。
対して外部キーで参照したいcardsテーブルのidがinteger型なので、型が合わずエラーになるようだ。

解決策

mysql - Migration to create table raises Mysql2::Error: Table doesn't exist - Stack Overflow
こちらが参考になったが、migrationの[5.1]の指定を5.0に戻すか、次のようにreferencesを使用しない形式に変える。

cards_tagsの生成(5.1版)
class CreateCardsTags < ActiveRecord::Migration[5.1]
  def change
    create_table :cards_tags, id: :integer do |t|
      t.integer :card_id, foreign_key: true
      t.integer :tag_id, foreign_key: true

      t.timestamps
    end
  end
end
43
34
2

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
43
34