Skip to content

27 Displaying Unthreaded Comments

Dave Strus edited this page Jul 16, 2015 · 1 revision

We're starting with just one level of comments per post. No threading.

Let's display unthreaded comments on posts/show, below the form.

app/views/posts/show.html.erb

  <ol id="comments">
    <% @post.comment_threads.each do |comment| -%>
      <li>
        <section class="comment-body">
          <%= comment.body %>
        </section>
      </li>
    <% end -%>
  </ol>

Let's display some metadata, similar to what we show for posts.

      <li>
        <div class="tagline" title="<%= comment.created_at %>">
          <%= comment.user.username %>
          <%= time_ago_in_words comment.created_at %> ago  
        </div>
        <section class="body">
          <%= comment.body %>
        </section>
      </li>

Not too tough so far, is it? Although it looks acceptable as-is, let's tweak the style a little.

app/assets/stylesheets/style.scss

#comments {
  padding-left: 20px;
  border-left: 1px dotted gray;
  li {
    list-style: none;
    margin-bottom: 15px;
    section.body {
      border: none;
      background-color: transparent;
      margin-top: 0;
      margin-bottom: 0;
      padding-bottom: 0;
      padding-left: 0;
    }
    .actions, .actions li {
      line-height: 12px;
      height: 12px;
      padding: 0;
    }
  }
  ol {
    margin-top: 15px;
    padding-left: 20px;
    border-left: 1px dotted gray;
  }
}

Let's add a default scope to the Comment model so comments are displayed in chronological order, oldest first.

app/models/comment.rb

  default_scope { order(:created_at) }

Does everything look OK? Let's add a comments link to posts' action links. Among other things, it will provide a way to get to the show page for a link post. Let's make it the first link in that section.

_app/views/posts/actions.html

  <li><%= link_to 'comments', post_path(post, anchor: 'comments') %></li>

That would be even nicer if it displayed the number of comments.

_app/views/posts/actions.html

  <li><%= link_to "#{post.comment_threads.length} #{'comment'.pluralize(post.comment_threads.length)}", post_path(post, anchor: 'comments') %></li>

This has the potential to trigger a lot of database queries on posts/index and categories/show. Let's preload our comments on those pages.

app/controllers/posts_controller.rb

  def index
    @posts = Post.includes(:comment_threads).page(params[:page])
  end

app/controllers/categories_controller.rb

  def show
    @category = Category.includes(posts: [:comment_threads]).find(params[:id])
    @posts = @category.posts.page(params[:page])
  end

Make sure everything works, and then let's commit before things get nuts.

$ git add .
$ git commit -m "Display unthreaded comments."