Skip to content

Instantly share code, notes, and snippets.

@lorenadl
Last active April 12, 2022 11:33
Show Gist options
  • Save lorenadl/a164e1c2228de9e388d55b55f22b3a4d to your computer and use it in GitHub Desktop.
Save lorenadl/a164e1c2228de9e388d55b55f22b3a4d to your computer and use it in GitHub Desktop.
[Rails] index: true vs foreign_key: true

index: true vs foreign_key:true in migration

In migration:

create_table :educations do |t| 
  t.belongs_to :profile, index: true, foreign_key: true
end

Index improve speed of data retrieval operations on database tables. When we write index: true to any column, it adds a database index to this column.

Foreign key enforce referential integrity. In the example above we have profile_id column in educations table which is foreign key of profiles table. It prevents a record from being entered into the educations table unless it contains a profile_id value that exists in the profiles table.

Remember that Rails 5 changed default behaviour for belongs_to, that now is has an implicit require: true, so the field is mandatory. To have the field optional, in the model specify:

belongs_to :profile, optional: true

Source: https://stackoverflow.com/questions/39503610/index-true-vs-foreign-key-true-rails?utm_medium=organic&utm_source=google_rich_qa&utm_campaign=google_rich_qa

@ndrslmpk
Copy link

Is this the defacto standard or would you instead also use a add_reference :educations, :profile, foreign_key: true for an existing table?

Would you prefer a add_reference :educations, :profile, foreign_key: true or a add_reference :educations, :profile, index: true, foreign_key: true?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment