On 3 August 2012 20:40, Steve Morrissey <[email protected]> wrote: > 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 > > def show > @article = Article.find(params[:id]) > @user = User.find(@article.user_id)
You did not mention that the article has a user_id. I thought that was comments that had user_id. However since it does have a user_id then assuming you have set up the models correctly you should be able to say @user = @article.user > @comments = @article.comments > impressionist(@snippet) > end > > 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. Again you should just be able to use comment.user.name If that does not work show us the most important information, which is how you have defined the relationships in the models (has_many, belongs_to etc). Colin -- You received this message because you are subscribed to the Google Groups "Ruby on Rails: Talk" group. To post to this group, send email to [email protected]. To unsubscribe from this group, send email to [email protected]. For more options, visit https://groups.google.com/groups/opt_out.

