You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Rails迁移报错:PG::DuplicateTable,目标索引已存在

解决Rails迁移中PostgreSQL重复索引错误

问题原因

Rails 的 t.references :parent(或t.belongs_to :parent)方法会自动为parent_id字段创建索引,你在迁移文件里又手动添加了t.index :parent_id,导致PostgreSQL尝试创建同名索引,触发PG::DuplicateTable错误。

修复步骤

  • 打开迁移文件20140517141938_create_content_pages.rb,删除手动添加的t.index :parent_id那一行。
  • 执行以下命令重置数据库并重新迁移:
    rake db:drop db:create db:migrate
    

正确的迁移文件示例

修改后的迁移文件应该类似这样,避免重复索引声明:

class CreateContentPages < ActiveRecord::Migration
  def change
    create_table :content_pages do |t|
      t.references :parent, null: false, foreign_key: true
      # 这里添加你的其他字段,比如标题、内容等
      
      t.timestamps
    end
    # 不要在这里手动添加t.index :parent_id
  end
end

内容的提问来源于stack exchange,提问作者Rabeya Khatun Muna

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.29 05:52:33