Bummer! This is just a preview. You need to be signed in with a Basic account to view the entire video.
Has Many Associations8:53 with Jay McGavren
Let's add a Comment model now, and then set up an association so we can add Comments to a Post.
- Let's add a Comment model now. We'll give it a
contentattribute with a type of
textto hold all the nice things our commenters have to say, and a
nameattribute with a type of
stringso we know who left it.
bin/rails g model Comment content:text name:string
- Don't forget to run
bin/rails db:migrate. That will add a
commentstable with our
contentcolumn to the database.
- Now, we need a
Postto add comments to.
post = Post.last
NoMethodError: undefined method 'comments' for #<Post...>
- This takes the symbol you specify,
:comments, and add a method with that same name to all
- Unlike with the Rails server, though, changes to your code aren't immediately available in the console. We need to
exitthe console first, then restart it with
- This takes the symbol you specify,
- Now we should be able to call our new
post = Post.last; post.comments
- Active Record attempts query
SELECT "comments".* FROM "comments" WHERE "comments"."post_id" = ?
no such column: comments.post_id
- Active Record attempts query
Active Record is looking for a column in the database that will allow it to associate comments with a
Post. We need to add the appropriate column. But what table should we add it on? The first thing you might attempt is to add several columns to the
posts table, each holding the ID of a record from the
comments table. But you remember the time we considered adding the comment text to the
posts table directly? We rejected that idea because no matter what number of columns we added, it would be too few in some cases, and too many in others. And this setup would give us the same problem.
So instead, we'll add a column on the
comments table, where each record will hold the ID of a record from the
posts table. All the comments with a
1 will refer back to the record with an
1 in the
posts table. Comments with a
3 will refer back to the post with an
3. Comments with a
7 will refer to the post with an
7. And so on.
This is a common practice in database design, and is known as adding a foreign key column to a table. The values that a column holds have to match the value of a primary key column, that is, the column that uniquely identifies a record, in a foreign table. In this case, the
post_id field in the
comments table is a foreign key because it refers to values in the
id column of the
posts table, which is that table's primary key. You can learn more about foreign keys in this video.
bin/rails generate migration AddPostToComments post_id:integer:index
indexsuffix will add an
add_indexmethod call to the migration.
add_indexcauses a database table to be indexed by a particular field, in this case the
post_idfield. Now, when we need to look up records with a particular
commentstable, our database won't have to look through the records one by one. Instead, it will just consult the index, which will point directly to all the records with the
post_idwe're looking for. Whenever you add a foreign key column to a table, you'll usually want to add an index on that column too, for speed's sake.
class AddPostToComments < ActiveRecord::Migration[5.0] def change add_column :comments, :post_id, :integer add_index :comments, :post_id end end
post = Post.first(You could also use
Post.find, or any other method that gets you a single
post.commentsreturns an empty list right now.
- To create a comment that's associated with a post:
comment = post.comments.build
comment.content = "Comment on first post"
comment.name = "Jay"
post.commentsnow returns a list that includes our new comment.
- To create a comment and save it immediately:
post.comments.create(content: "Cool!", name: "Alena")
- Added to list returned from
- To create and view comments on different post:
post = Post.last
post.comments.create(content: "Comment on last post", name: "Pasan")
Let's add a comment model to our blog app now.
We'll do that with bin/rails generate model.
We'll name the model Comment, with a capital C.
And we'll give it a content attribute with a type text to hold all the nice
things our commenters have to say.
And a name attribute with a type of string, so we know who left it.
That'll generate our model files as well as migration, and
don't forget to run bin/rails db:migrate.
That'll lay out a comments table with our content column to the database.
Now, let's run our rails console.
And we're going to need a post to add comments to.
So we'll say, post = Post, and we'll just grab the last one.
Now, let's try to take a look at the comments that are attached to our post.
We'll say, post.comments.
But this fails with no method error, undefined method comments.
For this to work, we're going to need to go into our post model,
and make a call to the class method has_many with a symbol of comments.
This will take the symbol that you specify, comments, and
add a method with that same name to all post model objects.
So let's save that and go back to our console.
Unlike with the real server,
changes to your code aren't immediately available in the console.
We need to exit the console first, and
then restart it with bin/rails console again.
Now, we should be able to call our new comments method.
So we'll call post = Post.last again to save the post object
in the post variable, and then we'll call post.comments.
This time, ActiveRecord attempts a query.
It tries to select all comment fields from the comments table, but
it only wants to select comments where the post_id equals
the specific post that we've requested here in the rails console.
But it's getting an error, no such column: comments.post_id.
ActiveRecord is looking for
a column in the database that will allow it to associate comments with a post.
We need to add the appropriate column, but what table should we add it on?
The first thing you might attempt is to add several columns to the post table,
each holding the id of a record from the comments table.
You remember the time we considered adding the comment text to the post table
We rejected that idea, because no matter what number of columns we added,
it would be too few in some cases, and too many in others.
And this setup would give us the same problem.
So instead, we'll add a column on the comments table,
where each record will hold the id of a record from the posts table.
All the comments with a post_id of 1,
we'll refer back to the record with an id of 1 on the post table.
Comments with a post_id of 3, we'll refer back to the post with an id of 3.
And comments with a post _id of 7, we'll refer to the post with an id of 7,
and so on.
This is a common practice in database design, and
is known as adding a foreign key column to a table.
The values that a column holds have to match the value of a primary key column,
that is, the column that uniquely identifies a record in a foreign table.
In this case, the post_id field in the comments table is a foreign key,
because it refers to values in the id column of the posts table,
which is that table's primary key.
If you'd like more info on foreign keys, check the teacher's notes.
So now we need to actually add the foreign key column to the comments table.
Let's exit out of our rails console.
And we're gonna run bin/rails generate
This name's a little bit magical, and
we'll talk about its components in just a moment.
The colon we're going to want to add is post_id.
It's going to be an integer, because the id of the post table is also an integer.
And we're going to want to make sure that this colon gets
indexed as well to speed up lookups.
So we're gonna type :index, after that, colon.
And that's gonna generate a migration file called add_post_to_comments.
Let's take a look at that right now.
We use this special format for the migration name.
We started with add, because we're adding a column.
Here's the name of the column we're adding.
And we ended it with To and
the name of the table that we want to add the column to.
Because we ended it with two comments, the migration generator knows that our
operations are going to be taking place against the comments table.
If you didn't use that specific format for the migration, then you might need to
add this attribute to the migration contents manually, which is okay.
We specified that we're adding a post_id column, which is of type integer, so
And here's the results of the index suffix that we added on the end.
It added an add_index method call to the migration.
Add_index causes a database table to be indexed by a particular field,
in this case, the post_id field.
Now, when we need to look up records with a particular post_id in the comments
table, our database won't have to look through the records one by one.
Instead, it'll just consult the index, which will point
directly to all the records with the post_id we're looking for.
Whenever you add a foreign key column to a table,
you'll usually want to add an index on that column too, for speed's sake.
Okay, now that we've generated the migration, we're gonna need to run it,
which we do with bin/rails db:migrate.
And that'll add the post_id column to the comments table and then index it.
Now, let's go back into bin/rails console, c for short.
And let's bring up a post again.
We'll say post = Post.first.
If we were to call the comments method, it would work but
it returns an empty list right now.
So let's create a comment that's associated with the post.
We'll say comment = post.comments.
And then we need to call a method on the comments collections, so we'll say, build.
That'll create a new comment that's associated with our post.
You can see the post_id 1 here at the end.
But not on the other attributes are populated,
then it's not safe to the database yet.
So let's set the common.content,
we'll set that = "Comment on first post".
Give a commenter name.
comment.name = "Jay", And let's save it.
And now, if we call post.comments, it'll return a list that includes our comment.
If we wanna create a comment and save it immediately,
we could use the create method.
So we say post.comments as before.
But this time, we're going to call the create method on that collection.
We'll set its content attribute to "Cool".
And we'll say the commenter's name as "Alena".
That'll be immediately saved to the database with those attributes.
And if we call post.comments again now, we'll see two comments in the results.
By the way, there's a useful method you can call in the rails console called pp,
it stands for pretty print.
So if we call pp with post.comments,
we can get a pretty formatted list of all the comments.
So now, we've got a couple comments on our first post.
Let's and create and view some comments on a different post.
We'll say, post = Post.last, instead of Post.first.
post.comments, and we'll create a new comment.
We'll set its content to, "Comments on last post".
And we'll say that this comment is from "Pasan".
If we were to say Post.last.comments, And
we'll pretty print that, we'll get the comment for the last post.
If we say Post.first.comments, we'll get the comments from the first post.
And if we say Comment.all, and we'll pretty print that,
we'll get a list for all the comments on all the posts.
Nice work, you've successfully set up your first rails association.
We set up a many association between the post model and the comments model.
You need to sign up for Treehouse in order to download course files.Sign up