Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a column unique and index it in a Ruby on Rails migration?

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.

like image 500
Tam Avatar asked Sep 19 '09 20:09

Tam


People also ask

What is index in rails migration?

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.

What is create unique index?

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.

Can you edit a migration file rails?

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.


1 Answers

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.

like image 93
ndp Avatar answered Sep 28 '22 05:09

ndp