LoginSignup
43
39

More than 3 years have passed since last update.

[Rails]referencesを使用した外部キー設定で沼った

Posted at

referencesを使用した外部キー設定

Railsreferencesを用いて外部キーの設定を行おうとしたら、

Mysql2::Error: Table 'テーブル名' doesn't exist: SHOW FULL FIELDS FROM ...

といったエラーがでてだいぶ時間を取られてしまったのでどう解決したかを備忘録として記します。

エラーとなった実装

エラーとなってしまったmigrationファイルは次のようなものでした。

table_namesというテーブルのカラムである
user_iduser.idに、
book_idbook.idに紐付けたい。


class ClassName  < ActiveRecord::Migration[5.1]
  def change
    create_table :table_names do |t|
      t.references :user, foreign_key: true,
      t.references :book, foreign_key: true
    end
  end
end

同じ事例を調査していたところ次のような記事を発見。
Rails5.1に移行後のmigrationファイルの注意

この記事によると、Rails5.1後に作成するmigrationファイルはデフォルトでidカラムにbigint型を使う(Mysqlの場合)
不都合が生まれるケースが生じる場合があるとのこと。

確かに今回私のケースでは、userがinteger型でbookがbigint型で行っている。

記事を参考にし、以下のようにコードを修正。


class ClassName  < ActiveRecord::Migration[5.1]
  def change
    create_table :table_names do |t|
      t.integer :user_id, foreign_key: true
      t.bigint :book_id, foreign_key: true
    end
  end
end

修正後、確かにエラーは消えるが、当たり前だがこれでは外部キー設定が何もできていない。。笑

解決策

とりあえず、型の関係でエラーとなっていることは分かった。
ということで、referencesを用いた上でtypeを指定してあげることに。


class ClassName  < ActiveRecord::Migration[5.1]
  def change
    create_table :table_names do |t|
      t.references :user, type: :integer, foreign_key: true,
      t.references :book, type: :bigint, foreign_key: true
    end
  end
end

これでうまいこと実行できた。
こんなことにすごく時間をかけてしまった。

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