Question: ❓❓❓

I would like to make a column unique in Ruby on Rails migration script. What is the best way to do it? Also is there a way to index a column in a table?

I would like to enforce unique columns in a database as opposed to just using :validate_uniqueness_of.

Good Answer: 👌👌👌

The short answer:

add_index :table_name, :column_name, unique: true

To index multiple columns together, you pass an array of column names instead of a single column name,

add_index :table_name, [:column_name_a, :column_name_b], unique: true

For finer grained control, there’s a “execute” method that executes straight SQL.

That’s it!

If you are doing this as a replacement for regular old model validations, just check to see how it works. I’m not sure the error reporting to the user will be as nice. You can always do both.


Categories: developerknowledge