Reputation: 233
There are posts, comments & users. I want to post number of comments for a specific user in comments list on Post show page. I know I need to define @user, but I don't know how to define it, so that it shows specific number for every user. User is author of the comment.
Post controller
def show
@post = Post.find(params[:id])
@comment = Comment.new
@comments = Post.find(params[:id]).comments.order(created_at: :desc)
@user = ???
end
Post /show action - error is for - @user.comments.count
<div class="row">
<% @comments.each do |comment| %><br>
<div class="col-sm-4"> <%= link_to comment.user.name, user_path(comment.user) %> <br>
<%= image_tag(comment.user.smallimage) %><%= @user.comments.count %>
</div>
<div class="col-sm-8"> <b><%= comment.title %>:</b>
<div>
<% if comment.content.length > 250 %>
<%= truncate(comment.content, length: 250) %>
<%= link_to_function '...Read more', "$(this).parent().html('#{escape_javascript comment.content}')" %>
<% else %>
<%= comment.content %>
<% end %>
</div>
</div>
<% end %>
</div>
Upvotes: 0
Views: 438
Reputation: 43298
If you define an @user
you will only have one user or a group of users that doesn't relate to your comments. You don't need it. You can just use the relationship between user and comment like this:
<%= comment.user.comments.count %>
Note that this will run a database query for each comment to get the total comment count for that user. For performance reasons you may want to use a counter cache for this instead.
Upvotes: 2
Reputation: 1159
If you defined the association in the post model belongs_to :user
then you can probably do @user = @comment.user
But, if that's the case then you can call that from the view with @comment.user.name
or something like that.
I'd like to see the whole codebase if you've pushed to GitHub.
Upvotes: 1