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.
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.
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.
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.
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.
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With