Variations on Foreign Key Migrations6:31 with Jay McGavren
There are many ways to add the foreign key column that's required by our has_many and belongs_to associations, and I want to take a moment to show you a couple more of them.
There are many ways to add the foreign key column that's required by our
belongs_to associations, and I want to take a moment to show you a couple more of them.
- If you want, you can use the
referencescolumn type in migrations instead.
bin/rails generate migration AddPostToComments post:references
- That will create a migration with a call to the
add_referencemethod instead of
add_referencetakes a symbol with a table name, and a symbol with the name of a model to add a foreign key for. It'll create a column whose name begins with that model name, and ends in
_id. And since it's always desirable to have an index on foreign key columns,
add_referencewill add an index as well. So
add_reference :comments, :postwill create a
post_idcolumn in the
commentstable just like
add_columndid, but it will also add an index on that column automatically.
foreign_key: trueargument will set up a foreign key constraint on databases that support it.
class AddPostToComments < ActiveRecord::Migration[5.0] def change add_reference :comments, :post, foreign_key: true end end
Without a foreign key constraint, we could create a comment with a
post_id field set to
999, even if there was no record in the
post table with an
999. With a foreign key constraint, the database would prevent such a record from even being saved. Foreign key constraints help keep bad data from sneaking into your database.
Note that the adapter for the SQLite database that Rails uses by default doesn't support foreign key constraints. Your migration will still work, and it's a good idea to get in the habit of adding the constraints in your migrations. But if you want the database to actually enforce the constraints, you'll need to switch to another database like MySQL or PostgreSQL.
If we know we're going to need an association when we're first creating a model, we can set the necessary columns up then, too.
- Let's re-generate the
Commentmodel. We can replace the two migrations with a single migration that creates the
commentstable and adds a
post_idcolumn along with the other columns:
rails g model Comment content:text name:string post:references.
- We can allow it to overwrite the existing model class file, as well as another file related to tests.
- Don't forget to run
- We should now be able to create comments associated with a post again.
You need to sign up for Treehouse in order to download course files.Sign up