Reputation: 343
I'm trying to show the avatar of each user who has commented in a topic. I pretty much have a Topic Model and a Comment Model. In my index page i have a list of all the topics created and a list of avatar of the user who commented but it only gets the list of the first topic and the images get repeated.
This is what i have in my index but I end up getting the avatar of each comment with repeated images.
<tbody>
<% @topics.each do |topic| %>
<th class="topic"> <%= link_to topic.title, topic %> </th>
<th class="category"><%= topic.category.title %></th>
<th class="users"><%= image_tag topic.user.avatar.url(:thumb)%></th>
<th class="replies"><%= topic.comments.count %> </th>
<th class="replies"></th>
<th class="activities"></th>
<% @comment.each do |comment| %>
<%= image_tag comment.user.avatar.url(:thumb) %>
<% end %>
<% end %>
</tbody>
My comments controller
class CommentsController < ApplicationController
def index
@topics = Topic.all
@comments = Comment.includes(:user)
end
def create
@comment = @commentable.comments.new(comment_params)
@comment.user_id = current_user.id
@comment.save
redirect_to @commentable
end
private
def comment_params
params.require(:comment).permit(:body)
end
end
Upvotes: 0
Views: 49
Reputation: 29124
You are displaying the user of only one comment.
<% @comment.each do |comment| %>
You probably need to get all comments of the topic instead. See below.
<% topic.comments.each do |comment| %>
To avoid N+1
issue, you can eager load the comments too
def index
@topics = Topic.includes(:comments => :user)
end
To display unique users, you can use Array#uniq with a block.
Assuming comments table has user_id
, as foreign key,
<% topic.comments.uniq(&:user_id).each do |comment| %>
Upvotes: 2