I have a question about rails 6 and model association with or without migrations. Let me be more specific. Let's say we want to place a foreign key inside users table which links to the id column of the courses table. Most of the tutorials and courses i run into follow this route:
My thought is, how about this:
or is it the same? Doesn't the second option create indexes as well whereas the first does not?
Which is a best practice?
add_reference
is meant to be a shortcut as part of the rails convention, under the hood, it will call add_column
and other options that you specify [you can check the code for rails-6 here]
while foreign keys are not required, they are considered a best practice because they guarantee referential integrity. you can read more about it here https://edgeguides.rubyonrails.org/active_record_migrations.html#foreign-keys
or is it the same? Doesn't the second option create indexes as well whereas the first does not?
having said that, your 2 migrations are not entirely the same even though they work the same (they achieve the same goal) - the second option will add an index by default unless you specify the option not to - I definitely agree with you about using add_reference
as this is an easier and more foolproof shortcut
of course, you can also achieve that manually by using your first migration by adding an index and a foreign key as well
add_column :users, :course_id, :integer
add_index :users, :course_id # uniq or not
add_foreign_key :courses, :users