LoginSignup
2
2

More than 5 years have passed since last update.

Railsでテーブルにリレーションを貼りたい&カラム名をテーブルとは別名にしたい場合。

Posted at

リレーションを作成する際、基本的にはカラム名は"[table名(単数系)]_id"となります。フォロー/フォロワー関連のテーブルの様に、1つのテーブルで複数のUserテーブルとのリレーションが必要になる場合、カラム名を変更しなくてはいけません。
今まで、integerでカラムを追加していたのですが、referencesで別名をつけることができる様です。
最近までこのやり方を知らなかったので、メモとして投稿させて頂きます。

UserテーブルとRelationshipテーブルを作成する例を記載します。
Migrationファイルのテーブル定義のコードになります。

テーブル作成

Userテーブル

create_table :users, unsigned: true do |t|
  t.string :email,              null: false, default: ""
  t.string :encrypted_password, null: false, default: ""
  t.string :name

  t.timestamps null: false
end

Relationshipテーブル

create_table :relationships, unsigned: true do |t|
  t.references :follower, foreign_key: { to_table: :users }, null: false, unsigned: true
  t.references :following, foreign_key: { to_table: :users }, null: false, unsigned: true

  t.timestamps null: false
end

foreign_key: { to_table: :users } というリレーション(外部キー)の書き方を知りませんでした><

【補足】

例として記載していますので、実際このままmigrateできるかは試していません。
あくまでメモとして・・・

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