Why did Rails 5 change "index" to "foreign key"?
Asked Answered
R

3

15

If you had this in Rails 4:

t.references :event, index: true

Now you could use foreign_key instead of index in Rails 5. I don't quite understand WHY they decided to do this, since the functionality remains the same, what you're adding is an INDEX, not a FOREIGN KEY to that column.

Radioactivity answered 29/9, 2016 at 12:11 Comment(1)
I honestly don't understand your question, the index option adds a database index, the foreign key one adds a database foreign key.Legwork
D
43

In Rails 5 - when we reference a model, index on the foreign_key is automatically created.

Migration API has changed in Rails 5 -

Rails 5 has changed migration API because of which even though null: false options is not passed to timestamps when migrations are run then not null is automatically added for timestamps.

Similarly, we want indexes for referenced columns in almost all cases. So Rails 5 does not need references to have index: true. When migrations are run then index is automatically created.

As an example - (Copying from http://blog.bigbinary.com/2016/03/01/migrations-are-versioned-in-rails-5.html)

When you run rails g model Task user:references

Rails 4 would generate

class CreateTasks < ActiveRecord::Migration
  def change
    create_table :tasks do |t|
      t.references :user, index: true, foreign_key: true
      t.timestamps null: false
    end
  end
end

And rails 5 would generate

class CreateTasks < ActiveRecord::Migration[5.0]
  def change
    create_table :tasks do |t|
      t.references :user, foreign_key: true
      t.timestamps
    end
  end
end
Depress answered 29/9, 2016 at 12:23 Comment(1)
Very well detailled answer. BUT, what if for whatever reason, I don't want the reference to be indexed? Or was it still indexed implicitly in Rails 4 even if I only have t.references :user, foreign_key: true ? --- And now, I wonder why they didn't even omit foreign_key: true too.Oakes
B
18

The index and foreign_key are different concepts, even if in Rails 5. So it's wrong to say the rails 5 changed “index” to “foreign key”.

The change from Rails 4 to Rails 5 is that the index option defaults to true, so you don't need to set it explicitly.

Method add_reference in rails 4.2.5

:index

Add an appropriate index. Defaults to false.


Method add_reference in rails 5.2

:index

Add an appropriate index. Defaults to true. See add_index for usage of this option.

That's why when you generate the references in rails 5 migration, you didn't see the index: true, because it's default.

Buffet answered 6/6, 2018 at 23:28 Comment(0)
B
5

foreign_key and index are completely different things (as you may judge from their names).

So nothing is being changed, you still can use two.

You can check out these docs for some more info on establishing associations in migrations.

Bonucci answered 29/9, 2016 at 12:14 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.