Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
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.
There are many ways to add the foreign_key column that's required by our has_many and
And I wanna take a moment to show you a couple more of them.
Let's undo our changes to the database by rolling back the latest migration.
We'll run bin/rails.
And we'll run the db:rollback task.
That'll go through the commands in the latest migration and undo them one by one.
Then let's get rid of the migration we created.
We're gonna do that with bin/rails destroy,
which you can consider to be the opposite of the generate command.
We're gonna destroy the migration named AddPostToComments.
That's the latest migration we created.
That'll go through,
find all the files that were created by the generator, and delete them.
Now let's redo our previous migration using the references column type instead.
So we're gonna run bin/rails generate.
We're gonna generate a migration.
And again, it'll be named AddPostToComments.
This time, instead of a type of integer, we're going to give it
a column name of post and a type of references.
That'll create a new migration file.
And the file will have a call to the add_reference method instead of
add_reference takes a symbol with a table name and a symbol with the name of
a model to add a foreign_key for, in this case, the post model.
It'll create a column whose name begins with that model name and
ends in underscore ID.
And since it's always desirable to have an index on foreign_key columns,
add_reference will add an index as well.
So add_reference :comments,
:post will create a post_id column in the comments table, just like add_column did.
But it'll also add an index on that column automatically.
The foreign_key: true argument will set up a foreign_key constraint
on databases that support it.
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 ID of 999.
But with a foreign_key constraint,
the database would prevent such a record from even being saved.
Note that the adapter for the SQL-like 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
But if you want the database to actually enforce the constraints,
you'll need to switch to another database like MySQL or PostgreSQL.
See the teacher's notes if you'd like more info on doing so.
Now that we have our new migration, let's try running it.
It'll add a post_id field back to our comments table again.
And if we launch a Rails console, we'll be able to add comments to our post again.
So if we were to take the first post and
create a comment on it with comments.create,
we'll give it content of HI.
And the commenter name is gonna be Jay.
And if we pretty print the list of the first post comments,
we can see the comment's been added.
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 start by getting our database back to the point it was at
before we created the comments model.
Since we've only set up the comments table on our development machine,
we can just undo the migrations that created it.
We can list out the migrations in our db/migrate directory with ls db/migrate.
You might need to use a slightly different command to list the directory contents if
you're on Windows.
We can see that the two most recent migrations are add_post_to_comments and
Let's roll back our migration that adds the post_id field to the comments table.
Then let's roll back the migration that created the comments table.
bin/rails db:rollback again.
Now let's get rid of those last two migrations.
The migration named AddPostToComments.
And then we'll also destroy the migration named CreateComments.
Now let's regenerate the comment model.
We can replace the two migrations with a single migration that creates the comments
table and adds a post_id column along with the other columns.
So we'll say bin/rails
generate model Comment.
We'll set up a content attribute of type text and
commenter name attribute of type string.
And post:references will set up the post_id field.
If it asks to overwrite any existing files, it should be okay to allow it.
We generated the migration, so don't forget to run bin/rails db:migrate.
And if we launch bin/rails console,
we should be able to create comments associated with post again.
So let's say post = Post.first,
And we'll give it content of Hi and a commenter name of Alena.
And if we run Post.first.comments, it should bring up our new comment.
Now you know several ways to setup a has_many association.
In the next few videos, we're going to take a look at some of the other
associations that Active Record supports
You need to sign up for Treehouse in order to download course files.Sign up