修改 join table 引用不同的 table 并重命名

Modify join table to reference different tables and rename

我目前有一个名为 leagues_questions 的 table,但在开发过程中我意识到 table 应该被称为 seasons_questions 并引用 season table 而不是 question table。我正在努力了解进行此更改的最佳方法。我的第一个想法是创建一个新的迁移来修改这个 table。这是我的尝试:

旧迁移:

def change do
  create table(:leagues_questions, primary_key: false) do
    add :id, :uuid, primary_key: true
    add :league_id, references(:leagues, on_delete: :nothing, type: :uuid), null: false
    add :question_id, references(:questions, on_delete: :nothing, type: :uuid), null: false

    timestamps()
  end
end

新迁移:

def change do
  alter table(:questions_leagues) do
    modify :question_id, :season_id
  end
end

我还需要更改 table 名称,但我想我可以处理。

我认为这行不通,我什至还没有真正尝试过,因为我不知道如何更改 references 部分。如何在迁移中修改 table 的引用列?

要重命名您需要做的列

rename table(:leagues_questions), :question_id, to: :season_id

然后你需要处理外键约束

我假设你已经尝试过这个:

alter table(:leagues_questions) do
  modify :season_id, references(:seasons, on_delete: :nothing, type: :uuid), null: false)
end

它没有用。您需要这样做:

drop constraint("leagues_questions", :leagues_questions_question_id_fkey)
alter table(:leagues_questions) do
  modify :season_id, references(:seasons, on_delete: :nothing, type: :uuid), null: false)
end

基本上首先删除现有约束。