Heads up! To view this whole video, sign in with your Courses account or enroll in your free 7-day trial. Sign In Enroll
Start a free Courses trial
to watch this video
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
Post
that it belongs to.- Go to
app/models/comment.rb
, and add:belongs_to :post
. - Now we can load up a
Comment
:comment = Comment.last
, and access thePost
it belongs to by calling its newpost
method:comment.post
. We already made all the database changes we needed when adding thehas_many :comments
association to thePost
class, so ourbelongs_to :post
association 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