Techioz Blog

複合主キーテーブルへの参照を含むテーブルを作成する

概要

複合主キーテーブルを作成しました。

class CreateWines < ActiveRecord::Migration[7.1]
  def change
    create_table :wines, primary_key: [:name, :producer_id] do |t|
      t.string :name

      t.timestamps
    end
  end
end

ここで、1 対多の関係を持つ別のテーブルを作成したいと思います。

class CreateWineItems < ActiveRecord::Migration[7.1]
  def change
    create_table :wine_items do |t|
      t.string :vintage
      t.references :wine, null: false, foreign_key: true
  end
end

db:merge でエラーを受け取りました。

PG::UndefinedColumn: ERROR:  column "id" referenced in foreign key constraint does not exist

私はテーブルの列とprimary_keyを渡す参照をいじっていました。

class CreateWineItems < ActiveRecord::Migration[7.1]
  def change
    create_table :wine_items do |t|
      t.string :vintage
      t.references :wine, null: false, foreign_key: { column: [:name, :producer_id],
                                         primary_key: [:name, :producer_id]}
      t.timestamps
    end
  end
end

そして、より具体的なエラーを受け取りました。

For composite primary keys, specify :column and :primary_key, where :column must
reference all the :primary_key columns from "wines"

複合主キーを持つテーブルとの参照関連付けを作成する正しい方法は何ですか?

解決策

リファレンスは CPK を (まだ) サポートしていません。列を追加してから fkey を手動で追加する必要があります。例:

create_table :wine_items do |t|
  t.string :vintage
  t.string :wine_name, null: false
  t.integer :wine_producer_id, null: false
  t.foreign_key :wines, column: %i[wine_name wine_producer_id], primary_key: %i[name producer_id]

  t.timestamps
end