Belongs To Associations2:20 with Jay McGavren
We can easily look up the Comments that belong to a Post. But the way things are set up now, we might have a little more trouble looking up the Post that a Comment belongs to. The belongs_to association can fix that.
We can easily look up the Comments that belong to a Post. But the way things are set up now, we might have a little more trouble looking up the Post that a Comment belongs to.
- Suppose all we had was a comment, and we wanted to get the
Postthat it belongs to.
- Go to
app/models/comment.rb, and add:
- Now we can load up a
comment = Comment.last, and access the
Postit belongs to by calling its new
comment.post. We already made all the database changes we needed when adding the
has_many :commentsassociation to the
Postclass, so our
belongs_to :postassociation works immediately.
- Go to
Now you know how to set up
belongs_to associations. Anytime you set up a
has_many association from your first model to a second model, you're going to want to set up a
belongs_to association from the second model back to the first.
You need to sign up for Treehouse in order to download course files.Sign up