Jack Gruber
Jack Gruber

Reputation: 163

Unable To Displaying Comments On A Post

I am adding comments to a post which save fine but I have been struggling to get them show more than one comments on a post. When I save it only shows the first comment posted.

Comments Controller:

class CommentsController < ApplicationController

  def create
    @micropost = Micropost.find_by(id: params[:micropost_id])
    @comment = 
@micropost.comments.create(params[:comment].permit(:body))
    if @comment.save
      flash[:success] = "Comment Posted"
    end
    redirect_to current_user
  end

end

def show
  @comment = Comment.find_by(id: params[:id])
end

end

In the view I have:

  <%= @comments.body %>

I can show one comment, but when I write another the first one only shows. I tried to loop over them in the view with a do loop but I then get an error stating undefined method .each for "text from comment":String

Maybe my show @comment needs improving or is there something I have to do in the view to get them all to display. The same do loops works for the posts, but I can seem to get it working for the comments.

I also have another minor issue when there is no comments saved, I can't view the post at all because there is no body existing. I assume I will have to write some sort of if/else to state if there is no body, display anyway.

Upvotes: 0

Views: 75

Answers (2)

Ashok Damaniya
Ashok Damaniya

Reputation: 303

what you are doing is fetching single comment and try to loop through that object , which is not possible.

what you want to do is display all the comments posted on 'Micropost' so what you need to do is just pass micropost_id in params and user where query like below

@comments = Comment.where(micropost_id: params[:micropost_id])  

then you can loop through that object in your .erb template

<% @comments.each do|comment| %>
  <%= comment.body %>
<% end %>

Upvotes: 1

Krupa Suthar
Krupa Suthar

Reputation: 680

In your posts controller's show method you should fetch comments and then you can show it in html page.

For example,

def show
 @post = Post.includes(:comments).find(params[:id])
end

and in your view file, you can iterate over comments like below,

@post.comments.each do |comment|
# you logic here
end

Upvotes: 2

Related Questions