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
.
An index is used to speed up the performance of queries on a database. Rails allows us to create index on a database column by means of a migration. By default, the sort order for the index is ascending. But consider the case where we are fetching reports from the database.
The CREATE UNIQUE INDEX command creates a unique index on a table (no duplicate values allowed) Indexes are used to retrieve data from the database very fast. The users cannot see the indexes, they are just used to speed up searches/queries.
Occasionally you will make a mistake when writing a migration. If you have already run the migration then you cannot just edit the migration and run the migration again: Rails thinks it has already run the migration and so will do nothing when you run rake db:migrate.
The short answer for old versions of Rails (see other answers for Rails 4+):
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
If you get "index name... is too long", you can add name: "whatever"
to the add_index method to make the name shorter.
For fine-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, check to see how it works. The error reporting to the user will likely not be as nice without model-level validations. You can always do both.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With