I am creating a table and specifying:
t.integer :random_id, :unique => true
It doesn’t add a unique index to random_id. But if I do:
ActiveRecord::Migration.add_index :test, :random_id, :unique => true
Then it works. What’s wrong with the first way?
THanks
I think you’ve explained it yourself in your 2 examples.
t.integer is a column definition, whereas add_index adds an index.
:unique is an index option and indexes are defined separately from the columns:
http://api.rubyonrails.org/classes/ActiveRecord/Migration.html
This allows you to define not only single columns as unique, but combinations of columns. This is particularly useful if you only want unique values within a certain scope, e.g. for ordering content within sections:
Slightly modified from here:
http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_index