rename_table:关系“TABLE_pkey”不存在

时间:2015-09-04 09:55:01

标签: ruby-on-rails ruby-on-rails-4 activerecord migration

Rails 4.1中的一个非常简单的迁移失败了,我不明白为什么。错误:

PG::UndefinedTable: ERROR:  relation "channel_entries_pkey" does not exist:
ALTER INDEX "channel_entries_pkey" RENAME TO "channels_projects_pkey"

以下是迁移:

class ConvertChannelEntriesToChannelsProjects < ActiveRecord::Migration

  def up
    remove_column :channel_entries, :position
    rename_table :channel_entries, :channels_projects
  end

  def down
    rename_table :channels_projects, :channel_entries
    add_column :channel_entries, :position, :integer
  end

end

一些背景:渠道和项目之间的连接是名为channel_entries的HM-THRU,以容纳额外的position。由于该位置已被删除,我将切换到一个简单的HABTM,按照惯例,连接表现在应该命名为channels_projects。

我记得,为_pkey自动创建了foreign_key索引,但channel_entries上从未存在任何外键。为什么rename_table想要重命名这个不存在的索引?

2 个答案:

答案 0 :(得分:2)

想出来,一个旧的迁移并没有完全发挥作用,并且没有发现约束。

答案 1 :(得分:1)

为类似问题添加我的解决方案。 以下是运行迁移时的错误

01 PG::UndefinedTable: ERROR:  relation "fundraise_stories_pkey" does not exist
01 : ALTER INDEX "fundraise_stories_pkey" RENAME TO "fundraisers_pkey"

通过pgadmin连接到数据库,并为表fundraise_stories选择约束。它显示约束名称为“ fundrise_stories_pkey”。 因此这是一个旧错误,因为约束名称与表名称不匹配。

解决方案:

  1. 在表的“约束”部分下找到现有索引名称。就我而言,是“ fundrise_stories_pkey”
  2. 重命名表之前重命名索引
  3. 最后,重命名表。

下面是修改后的迁移,以在重命名表之前重命名索引。

def self.up
    execute "ALTER INDEX fundrise_stories_pkey RENAME TO fundraise_stories_pkey;"
    rename_table :fundraise_stories, :fundraisers
end

日志

D, [2020-02-02T17:16:27.428294 #7363] DEBUG -- :    (0.2ms)  BEGIN
== 20200127102616 RenameFundraiseStoryTableToFundraisers: migrating ===========
-- execute("ALTER INDEX fundrise_stories_pkey RENAME TO fundraise_stories_pkey;")
D, [2020-02-02T17:16:27.434366 #7363] DEBUG -- :    (5.5ms)  ALTER INDEX fundrise_stories_pkey RENAME TO fundraise_stories_pkey;
   -> 0.0061s
-- rename_table(:fundraise_stories, :fundraisers)
D, [2020-02-02T17:16:27.435722 #7363] DEBUG -- :    (0.7ms)  ALTER TABLE "fundraise_stories" RENAME TO "fundraisers"
D, [2020-02-02T17:16:27.438769 #7363] DEBUG -- :    (0.3ms)  ALTER TABLE "public"."fundraise_stories_id_seq" RENAME TO "fundraisers_id_seq"
D, [2020-02-02T17:16:27.439334 #7363] DEBUG -- :    (0.2ms)  ALTER INDEX "fundraise_stories_pkey" RENAME TO "fundraisers_pkey"
D, [2020-02-02T17:16:27.445452 #7363] DEBUG -- :    (0.8ms)  ALTER INDEX "index_fundraise_stories_on_bank_account_id" RENAME TO "index_fundraisers_on_bank_account_id"
D, [2020-02-02T17:16:27.446153 #7363] DEBUG -- :    (0.3ms)  ALTER INDEX "index_fundraise_stories_on_creator_id_and_creator_type" RENAME TO "index_fundraisers_on_creator_id_and_creator_type" 
   -> 0.0131s
== 20200127102616 RenameFundraiseStoryTableToFundraisers: migrated (0.0193s) ==