htmlruby-on-railsfor-loopruby-on-rails-4

How do I rearrange order of comments?


I'm making a comment system, and it's a little messed up. It's listing comments from old to new, when I need it to go in the reverse order (newest on top). How do I do this?

Code: (/app/views/comments/_comment.html.erb)

<%= div_for comment do %>
        <p>
                <strong>
                        Posted <%= time_ago_in_words(comment.created_at) %> ago
                </strong>
                <br/>
                <%= comment.body %>
        </p>
<% end %>

Edit: Here is the comments controller:

class CommentsController < ApplicationController
    def create
        @post = Post.find(params[:post_id])
        @comment = @post.comments.create(params[:comment].permit(:commenter, :body))
        respond_to do |format|
            format.html { redirect_to @post }
            format.js
        end
    end
end

Solution

  • In your Comment model, add:

    default_scope -> { order('created_at DESC') }
    

    This way, @post.comments will be properly ordered.