リレーションを作成する際、基本的にはカラム名は"[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できるかは試していません。
あくまでメモとして・・・