简体   繁体   中英

How do I reverse a Postgresql unique index constraint in a rails migration?

I created a unique index on my model like so:

add_index(:courses, :name, unique: true)

I no longer require the name to be unique. I think I have the same problem as this person , so I worked through those suggestions to no avail.

I receive errors like "ActiveRecord::RecordNotUnique: PG::UniqueViolation: ERROR: duplicate key value violates unique constraint "index_courses_on_name" when I try to add a record with the same name.

To remove the unique constraint I've tried:

  1. remove_index :courses, :name

    (migration succeeds, but later I get the same error suggesting there is still a uniqueness constraint)

  2. execute "ALTER TABLE courses DROP CONSTRAINT unique_index_courses_on_name"
  3. execute "ALTER TABLE courses DROP CONSTRAINT index_courses_on_name"
  4. execute "ALTER TABLE courses DROP CONSTRAINT unique_name"
  5. execute "ALTER TABLE courses DROP CONSTRAINT name"
  6. execute "ALTER TABLE courses DROP INDEX index_courses_on_name"
  7. execute "ALTER TABLE courses DROP INDEX courses_on_name"
  8. execute "DROP INDEX unique_courses_name"

(PG::UndefinedObject: ERROR: index "unique_courses_name" does not exist)

  1. execute "ALTER TABLE courses disable CONSTRAINT unique_courses_name"

(PG::SyntaxError: ERROR: syntax error at or near "CONSTRAINT" LINE 1: ALTER TABLE courses disable CONSTRAINT unique_courses_name)

  1. execute "ALTER TABLE courses DROP INDEX unique_courses_name"

I'm on psql 9.4.4, Rails 4.2, and my last ounce of sanity. Thanks everyone.

I think unique will be removed if you remove the old index and add it again

class RemoveUniqueFromCoursesName < ActiveRecord::Migration
  def change
    remove_index(:courses, :name)
    add_index(:courses, :name)
  end
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM