Search code examples
ruby-on-railsruby-on-rails-6rails-migrations

Rails 6 & Model Association and/or Migrations


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:

  1. create a migration with add_column :users, :course_id, :integer
  2. place has_one or has_many and belongs_to to the appropriate models. And that's it.

My thought is, how about this:

  1. create a migration with add_reference :users, :course, foreign_key: true
  2. place the appropriate has_one/has_many and belongs_to to the apropriate models.

or is it the same? Doesn't the second option create indexes as well whereas the first does not?

Which is a best practice?


Solution

  • 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