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
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 aadd_reference :educations, :profile, index: true, foreign_key: true
?