Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I remove a unique constraint from a database column in Rails?

I created a table using the following migration:

class CreateProfilePictures < ActiveRecord::Migration   def change     create_table :profile_pictures do |t|       t.integer :user_id, null: false       t.integer :picture_id, null: false       t.timestamps null: false     end      add_index :profile_pictures, :user_id, unique: true     add_index :profile_pictures, :picture_id, unique: true   end end 

I tried to remove the constraint with the following:

class FixProfilePic < ActiveRecord::Migration   def change     change_column :profile_pictures, :picture_id, :integer, unique: false   end end 

I still get a unique constraint violation error if I try to use the same picture_id in more than one place. What is the proper way to remove the uniqueness constraint from picture_id?

like image 680
Daniel Avatar asked Nov 03 '15 09:11

Daniel


People also ask

How do I check if a column has a unique constraint?

To check for a unique constraint use the already provided method: select count(*) cnt from user_constraints uc where uc. table_name='YOUR_TABLE_NAME' and uc.

What will happen if a column has unique key constraint?

When we will add a UNIQUE constraint on the same column multiple times then MySQL will create the index on that column for a number of times we have added the UNIQUE constraint.

How remove unique from table in SQL?

The syntax for dropping a unique constraint in MySQL is: ALTER TABLE table_name DROP INDEX constraint_name; table_name.


1 Answers

You must remove your index with:

remove_index :profile_pictures, :picture_id 

and add it again with:

add_index :profile_pictures, :picture_id 

ActiveRecord::Migration

like image 184
dthal Avatar answered Oct 13 '22 13:10

dthal