0xSina
0xSina

Reputation: 21553

ActiveRecord migration :unique => true being ignored?

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

Upvotes: 2

Views: 1467

Answers (1)

dorianm
dorianm

Reputation: 253

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:

add_index(:post_position_within_section, [:position, :sections_id], :unique => true)

Slightly modified from here: http://apidock.com/rails/ActiveRecord/ConnectionAdapters/SchemaStatements/add_index

Upvotes: 4

Related Questions