Rails迁移因“外键约束失败”而被阻止

时间:2019-03-09 05:47:51

标签: ruby-on-rails

当我尝试运行相对简单的rails迁移以删除列时:

class Removetopicsfromquestions < ActiveRecord::Migration[5.2]
  def change
    change_table :questions do |t|
      t.remove :topic_id
    end
  end
end

由于“外键约束”而失败:

rails aborted!
StandardError: An error has occurred, this and all later migrations canceled:

SQLite3::ConstraintException: foreign key constraint failed: DROP TABLE "questions"
/usr/local/rvm/gems/ruby-2.4.1/gems/sqlite3-1.3.13/lib/sqlite3/statement.rb:108:in `step'
/usr/local/rvm/gems/ruby-2.4.1/gems/sqlite3-1.3.13/lib/sqlite3/statement.rb:108:in `block in each'
/usr/local/rvm/gems/ruby-2.4.1/gems/sqlite3-1.3.13/lib/sqlite3/statement.rb:107:in `loop'
/usr/local/rvm/gems/ruby-2.4.1/gems/sqlite3-1.3.13/lib/sqlite3/statement.rb:107:in `each'
/usr/local/rvm/gems/ruby-2.4.1/gems/sqlite3-1.3.13/lib/sqlite3/database.rb:152:in `map'
/usr/local/rvm/gems/ruby-2.4.1/gems/sqlite3-1.3.13/lib/sqlite3/database.rb:152:in `block in execute'
/usr/local/rvm/gems/ruby-2.4.1/gems/sqlite3-1.3.13/lib/sqlite3/database.rb:95:in `prepare'
/usr/local/rvm/gems/ruby-2.4.1/gems/sqlite3-1.3.13/lib/sqlite3/database.rb:137:in `execute'
etc...

表的当前外观如下:

create_table "questions", force: :cascade do |t|
    t.integer "topic_id"
    t.string "name"
    t.text "explanation"
    t.boolean "published", default: true
    t.string "usage", default: "Free Quiz", null: false
    t.datetime "created_at", null: false
    t.datetime "updated_at", null: false
    t.string "variant", default: "fill", null: false
    t.string "correct"
    t.string "alt_one"
    t.string "alt_two"
    t.string "alt_three"
    t.string "editor"
    t.boolean "accepted"
    t.string "reference"
    t.text "context"
    t.string "questionable_type"
    t.integer "questionable_id"
    t.index ["questionable_type", "questionable_id"], name: "index_questions_on_questionable_type_and_questionable_id"
  end

知道我在做什么错吗?

1 个答案:

答案 0 :(得分:0)

我假设您在架构的底部有类似的内容?

add_foreign_key "questions", "topics"

Rails无法从表中删除此列,因为添加了外键。在您的迁移文件中尝试以下操作:

def change
  remove_reference :questions, :topic, index: true, foreign_key: true
end