LoginSignup
7
4

More than 5 years have passed since last update.

[rails5]文字列のカラムに外部キー制約を設定する方法

Posted at

Railsでカラムに外部キー制約を設定する際に、文字列のカラムに設定したい時があると思います。
Railsで文字列のカラムに外部キー制約を設定する方法を記載します。

文字列のカラムに外部キー制約を設定する方法

reference型のカラムにforeign_key: truetype: :stringを設定することで文字列のカラムに外部キー制約を設定できます。
type: :stringの記載がないとデフォルトで数値型になってしまうため、外部キーの参照先が文字列の場合、型が一致せずエラーがでます。

サンプルコードは下記になります。

create_table.rb
class InitTables < ActiveRecord::Migration[5.0]
    def change
        create_table :users, id: false do |t|
          t.column :id, 'VARCHAR(10) NOT NULL PRIMARY KEY' # 外部キー参照先
          t.timestamps
        end

        create_table :hoge do |t|
          t.references :user, foreign_key: true, type: :string # 外部キー参照元
          t.timestamps
        end
    end
end

まとめ

カラムをreference型とし、foreign_key: truetype: :stringを記載することで文字列のカラムに外部キー制約をかけることができます。

参照先のカラムが文字列で、type: :stringを記載しないと下記エラーがでます。

Mysql2::Error: Cannot add foreign key constraint

これは参照先のidが文字列なのに対して、デフォルトでは参照元カラムが数値型で設定されるためです。
type: :stringを設定することで型を文字列で一致させることができます。

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