1
0

More than 1 year has passed since last update.

【Rails】マイグレーションで文字列の外部キー定義をより簡単に書く方法

Posted at

環境

Rails 6.0.1
Ruby 2.6.3
PostgreSQL 11.16

状況

rails db:migrateしたとき、外部キーが文字列なのにreferencesで外部キーを定義しようとするとエラー

PG::DatatypeMismatch: ERROR:  foreign key constraint "fk_rails_640ba59391" cannot be implemented
DETAIL:  Key columns "user_id" and "id" are of incompatible types: bigint and character varying
db/migrate/2022090909090_create_posts.rb
def change
  create_table :posts do |t|
     t.references :user, null: false, foreign_key: true
     t.string :title, null: false
     t.text :content, null: false

     t.timestamps
  end
end

解決法:一般的な方法

add_foreign_keyで外部キーを設定する。

db/migrate/2022090909090_create_posts.rb
def change
  create_table :posts do |t|
     t.string :title, null: false
     t.text :content, null: false
     t.string :user_id, null: false

     t.timestamps
  end

  add_foreign_key :posts, :users
end

解決法:便利な方法

referencestypeを指定することで文字列の外部キーを定義できる。

db/migrate/2022090909090_create_posts.rb
def change
  create_table :posts do |t|
     t.references :company, null: false, foreign_key: true, type: :string
     t.text :content, null: false
     t.string :user_id, null: false

     t.timestamps
  end
end
1
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
1
0