26

I'm writing a migration that involves a foreign key. Looking at my colleagues code, I see that he has added the line: t.reference :tablename, index: true

The t.reference part makes sense, but I don't know what index: true means. Can anyone tell me? I haven't been able to find that in the docs.

Note: This is not a duplicate of: Rails ActiveRecord::Migration what is the difference between index: true and add_index? Which only diffs the two, but doesn't explain what they do.

Community
  • 1
  • 1
kingsfoil
  • 3,795
  • 7
  • 32
  • 56

1 Answers1

26

index: true adds a database index to the referenced column. For example, if creating a :products table:

create_table :products do |t|
  t.references :user, index: true
end

That will create a non-unique index on the user_id column in the products table named index_products_on_user_id.

infused
  • 24,000
  • 13
  • 68
  • 78
  • 6
    What I was also confused on was what a database index is. I found the wiki article [here](http://en.wikipedia.org/wiki/Database_index) to be helpful. – kingsfoil Aug 05 '14 at 18:53
  • @alex0112 If you found the article helpful, please post a new answer sharing your findings and stuff. Some people do not check out the comments. – onebree Jul 09 '15 at 13:19
  • 2
    For some reason I had to do `t.references` plural for this to work. Not sure why, `rake db:migrate` spit out the error and suggested that I use `references` instead of reference for anyone looking at this using rails 5.X.X - this was also with `--database=postgresql` flag in `rails new` command. – Devon Kiss Feb 25 '17 at 17:53