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.
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.
The :foreign_key option lets you set the name of the foreign key directly. The associations between your Post and Comment model classes should look like this: class Post < ActiveRecord::Base has_many :comments end class Comment < ActiveRecord::Base belongs_to :post end.
Active Record is the M in MVC - the model - which is the layer of the system responsible for representing business data and logic. Active Record facilitates the creation and use of business objects whose data requires persistent storage to a database.
A Rails migration is a tool for changing an application's database schema. Instead of managing SQL scripts, you define database changes in a domain-specific language (DSL). The code is database-independent, so you can easily move your app to a new platform.
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
.
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