Welcome to the Treehouse Community
Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.
Looking to learn something new?
Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.
Start your free trial
Brandon Barrette
20,485 PointsTrouble with Associations
So I'm adding a very basic forum to my site and am having some trouble calling the right associations (I know it's a newbie mistake, but can't seem to figure out where my thinking is wrong.)
I have forums -> topics -> posts.
Forum: has_many topics
Topics: has_many posts, belongs_to forum, belongs_to user
Posts: belongs_to topic, belongs_to user
Now, in the forum/show page, I want to list all the topics for that forum (and that is working with the following code) <table class="table table-striped"> <tr> <th>Topic</th> <th>Last Reply</th> <th>Number of Replies</th> </tr> <% @forum.topics.each do |topic| %> <tr> <td> <h4><%= link_to topic.title, forum_topic_path(@forum, topic.id) %></h4><br/> Started by: <%= topic.user.full_name %> </td> <td></td> <td> <%= topic.posts.count %> </td> </tr> <% end %> </table>
And here's the show action in the controller:
def show
@forum = Forum.find(params[:id])
@topic = @forum.topics
add_breadcrumb @forum.title, forum_path(@forum)
respond_to do |format|
format.html # show.html.erb
format.json { render json: @forum }
end
end
Now, I have the count working (in that it's counting the number of posts correctly for each topic), but I want to call the last post for each topic to display the time and the user who posted last. This is where I am running into difficulties.
Any ideas? I'm able to get the last post by calling:
topic.posts.last
But am unsure how to get out the user and created_at column.
Any help would be great! Thanks!
1 Answer
Drake Ramming
5,373 PointsEdit for clarity
It's not pretty but should work. Call the desired properties on the last post object you retrieve from topic.posts.last
<%= topic.posts.last.created_at %> #return the time of the last post
<%= topic.posts.last.user.full_name %> #return the last post user object & call full_name method
Brandon Barrette
20,485 PointsBrandon Barrette
20,485 PointsThat actually doesn't work =(
I tried that originally and I end up with this:
undefined method `created_at' for nil:NilClassBecause topic.posts.last returns this:
#<Post:0x00000103553ad0>And I'm not sure how to deal with that.