为什么会出现此重复的列错误?

时间:2019-09-10 21:35:20

标签: ruby-on-rails ruby postgresql activerecord

我正在尝试向表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“学生”添加“活动”布尔默认值“ t”`

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

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

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

4 个答案:

答案 0 :(得分:2)

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

  1. 列出数据库

    \l
    
  2. 连接数据库

    \c your_app_database_name
    
  3. 列出表格列

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

    ALTER TABLE students DROP COLUMN active
    

答案 1 :(得分:1)

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

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

ALTER TABLE students DROP COLUMN active

答案 2 :(得分:0)

您可以按照上述解决方案进行操作,即先从数据库中删除该列,然后再运行迁移。最有可能发生的事情是,您创建并运行了一些迁移,但是后来删除了该迁移文件而没有进行class AddActiveToStudents < ActiveRecord::Migration[5.0] def change unless column_exists? :students, :active add_column :students, :active, :boolean, default: true end end end

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

rand_value = random()
for i in range(len(array)):
    rand_value -= probabilities[i]
    if rand_value <= 0:

答案 3 :(得分:0)

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

最后我通过以下方式将其删除:

  1. 进入控制台

rails console

  1. 删除列

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

相关问题