views:

1032

answers:

2

Hello,

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

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

Thanks,

Tam

+8  A: 

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]

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.

ndp
+1 for suggesting continuing to use the validates_uniqueness_of. The error handling is much cleaner using this method for the cost of a single indexed query I would suggest he does both
Steve Weet
I tried that it doesn't seem to work! I could insert two record with the column_name that I defined as unique! I'm using Rails 2.3.4 and MySql any ideas?
Tam
I used you second suggestion by using execute: execute "ALTER TABLE users ADD UNIQUE(email)" and it works! not sure why the first one didn't would be interested in knowing
Tam
Tam-- if this answer worked for you can you accept it? It improves your (visible) accept rate, and makes people more likely to answer your questions.
ndp
A: 

For solve problem of adding unique index after creating table you can use 1) rake:db migrate VERSION=0 2) rake:db migrate instead of rake db:setup

Oleksii