ruby 创建引用复合主键表的表

pw9qyyiw  于 2023-10-17  发布在  Ruby
关注(0)|答案(1)|浏览(132)

我创建了一个复合主键表:

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

现在我想创建另一个具有一对多关系的表:

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:migrate中收到错误:

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"

如何正确地创建与具有复合主键的表的引用关联?

a11xaf1n

a11xaf1n1#

references不支持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

相关问题