Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change column in Rails to be unique

I know many similar questions have been asked before but I haven't found this question exactly (maybe it's just not possible).

So I have a Column_A in my Rails table (using MySQL). Recently we've had the need to enforce uniqueness on this column.

Is it possible to do a change on this column to make it unique?

The only other solution I came up with is to create a temporary unique column and shuffle everything around. Which would be a pain.

Thanks!

like image 926
9TrSl9IAlaLfDmffagsw Avatar asked Nov 20 '15 16:11

9TrSl9IAlaLfDmffagsw


People also ask

How do I rename a column in Rails?

If you happen to have a whole bunch of columns to rename, or something that would have required repeating the table name over and over again: rename_column :table_name, :old_column1, :new_column1 rename_column :table_name, :old_column2, :new_column2 ...

How do I change migration in Rails?

Go to /db/migrate folder and edit the migration file you made.


1 Answers

Simple two step process:

1: Create a migration

change_column :table_name, :column_name, :string, unique: true

2: Add validation in your model

validates_uniqueness_of :column_name
like image 116
Padhu Avatar answered Sep 30 '22 06:09

Padhu