9TrSl9IAlaLfDmffagsw
9TrSl9IAlaLfDmffagsw

Reputation: 405

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!

Upvotes: 10

Views: 10588

Answers (2)

Kris
Kris

Reputation: 19948

You can add an index as such:

add_index :table_name, :column_name, unique: true
  • rails 5.2

Upvotes: 5

Padhu
Padhu

Reputation: 1580

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

Upvotes: 22

Related Questions