I’m working on a into rails project in parallel with a book I’m reading.
I have 3 models/controllers that I’m trying to get to interact properly:
user, article, comment
Each article can have many comments, each comment is made by 1 user.
Currently I’m able to get the article to show the comment content and
the user_id of the commenter. But what I’m tying to do is get the
username of the commenter based on that user_id.
Here is part of my controller for the Article
@article = Article.find(params[:id])
@user = User.find(@article.user_id)
@comments = @article.comments
Each comment contains the following: content, user_id, article_id.
I can get the content and the user_id’s associated to the article
<%= comment.content %>
<%= comment.user_id %>
This is a test comment user_id: 14
This is yet another thrilling test comment user_id: 15
What I’d like is comment.username so I can get the users name, but that
is throwing me for a loop. Making the connection between my users object
and the comments object.
I just don’t know how to get the username associated with that user_id
from the users table. I’ve made it through my Rails Tutorial book,
however it didn’t cover anything like this and a couple hours of
google-fu haven’t yielded anything.
Any assistance is greatly appreciated!