Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why did Rails 5 changed "index" to "foreign key"?

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.

like image 850
anemaria20 Avatar asked Sep 29 '16 12:09

anemaria20


People also ask

Why is it a good idea to index foreign keys?

It is highly recommended to create an index on the foreign key columns, to enhance the performance of the joins between the primary and foreign keys, and also reduce the cost of maintaining the relationship between the child and parent tables.

What is the difference between index and foreign key?

an index on a table is a data structure that makes random access to the rows fast and efficient. It helps to optimize the internal organization of a table as well. A foreign key is simply a pointer to a corresponding column in another table that forms a referential constraint between the two tables.

Is index automatically created on foreign key?

MySQL requires that foreign key columns be indexed; if you create a table with a foreign key constraint but no index on a given column, an index is created. Information about foreign keys on InnoDB tables can also be found in the INNODB_FOREIGN and INNODB_FOREIGN_COLS tables, in the INFORMATION_SCHEMA database.

What is index in rails migration?

An index is used to speed up the performance of queries on a database. Rails allows us to create index on a database column by means of a migration. By default, the sort order for the index is ascending. But consider the case where we are fetching reports from the database.


1 Answers

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
like image 103
Pramod Solanky Avatar answered Oct 24 '22 21:10

Pramod Solanky