Railsでreferences型のカラム名を参照先のテーブル名と別の名前にするには

Ruby on Railsのモデル作成における、「references型を参照先のモデル名と別の名前で追加したい」というケースの解決方法を紹介します。

新規モデルにreferences型を定義する場合

migrationファイルにおいて、t.referencesメソッドの:foreign_keyオプションに:to_tableを使用することで解決できます。

例えば、Profileモデルのカラムとして、Foodモデルを参照先とする:favorite_foodというreferences型を定義する場合は、以下のように記述します。

# Rails7.0の場合
class CreateProfiles < ActiveRecord::Migration[7.0]
  def change
    create_table :profiles do |t|
      t.string :name, null: false
      t.references :favorite_food, foreign_key: { to_table: :foods }
      t.timestamps
    end
  end
end

注意点として、参照先モデル名は複数形にする必要があります。

 

既存モデルにreferences型を追加する場合

既存のモデルに追加する際は、add_referenceメソッドの:foreign_keyオプションに:to_tableを使用することで解決できます。

class AddFavoriteFoodToProfiles < ActiveRecord::Migration[7.0]
  def change
    add_reference :profiles, :favorite_food, foreign_key: { to_table: :foods }
  end
end

 

以上となります。ご質問等ありましたら、コメント欄にてお願いします。

参考:ActiveRecord::ConnectionAdapters::SchemaStatements

コメント

タイトルとURLをコピーしました