【问题标题】:Why is this duplicate column error appearing?为什么会出现此重复列错误?
【发布时间】:2019-09-10 21:35:20
【问题描述】:

我正在尝试将新列 active 添加到我的表 students

我运行 rails g migration add_active_to_students active:boolean 来生成此迁移:

class AddActiveToStudents < ActiveRecord::Migration[5.0]
  def change
    add_column :students, :active, :boolean, default: true
  end
end

但是当我运行rails db:migrate 时,我得到了这个错误:

PG::DuplicateColumn:错误:关系“学生”的“活动”列已存在 : ALTER TABLE "students" ADD "active" boolean DEFAULT 't'`

如您所见,students 中实际上没有 active 列:

create_table "students", force: :cascade do |t|
    t.integer  "club_id"
    t.string   "email"
    t.string   "address_line_1"
    t.string   "address_line_2"
    t.string   "city"
    t.string   "state"
    t.integer  "postcode"
    t.string   "phone1"
    t.string   "phone2"
    t.string   "first_name"
    t.string   "last_name"
    t.date     "dob"
    t.datetime "created_at",      null: false
    t.datetime "updated_at",      null: false
    t.string   "picture"
    t.integer  "payment_plan_id"
    t.string   "parent1"
    t.string   "parent2"
    t.string   "size"
    t.text     "notes"
    t.index ["club_id"], name: "index_students_on_club_id", using: :btree
  end

那么为什么会出现这个错误呢?

【问题讨论】:

  • 删除您创建的迁移文件,然后运行 ​​rails db:migrate 并再次检查您的 db/schema.rb(它应该重新生成一个新文件)。如果您缺少应该创建该列的迁移文件(您应该检查),那么您可能已经以其他方式创建了它; (手动,在测试时在另一个分支中并且您忘记回滚)因此考虑您可能需要撤消所做的操作(手动删除列,切换回其他分支并回滚)以便您可以根据需要创建迁移

标签: ruby-on-rails ruby postgresql activerecord


【解决方案1】:

我按照@demir 发布的步骤发现,是的,该列在数据库中,但没有在架构中列出。 ALTER TABLE students DROP COLUMN active 没有给出错误消息,但它也没有删除该列。

最后我通过以下方式删除了它:

  1. 进入控制台

rails console

  1. 删除列

ActiveRecord::Base.connection.remove_column :students, :active

【讨论】:

    【解决方案2】:

    您可能以某种方式添加了它。你检查过PG数据库吗?连接到应用程序数据库并查看是否有活动字段。

    1. 列出数据库

      \l
      
    2. 连接数据库

      \c your_app_database_name
      
    3. 列出表格列

      \d+ students
      
    4. 检查活动字段,如果存在则将其删除。

      ALTER TABLE students DROP COLUMN active
      

    【讨论】:

      【解决方案3】:

      您的数据库中有此列,但它没有转储到您的schema.rb。可能迁移在添加列后停止,但在写入 schema.rb 之前停止?

      您可以手动删除此列,运行 rails dbconsole 然后:

      ALTER TABLE students DROP COLUMN active
      

      【讨论】:

        【解决方案4】:

        您可以按照上述解决方案,即先从数据库中删除列,然后运行迁移。最有可能发生的事情是,您创建并运行了一些迁移,但后来删除了该迁移文件而没有执行db:rollback

        您可以考虑的另一种选择是进行有条件的迁移,例如:

        class AddActiveToStudents < ActiveRecord::Migration[5.0]
          def change
            unless column_exists? :students, :active
              add_column :students, :active, :boolean, default: true
            end
          end
        end
        

        【讨论】:

        • 如果是这种情况,列将存在 om schema.rb
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2021-08-04
        • 2023-03-30
        • 2021-03-29
        • 2022-01-04
        • 2018-12-06
        • 2021-01-08
        • 1970-01-01
        相关资源
        最近更新 更多