Search code examples
ruby-on-railsrubycomments

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.


Solution

  • 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