Reputation: 103
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
Upvotes: 0
Views: 149
Reputation: 42899
Using default scopes can easily be confusing, because if I tried Comment.order(:id)
I would actually get select * from comments order by created_at desc, id asc
which might take time in debugging wondering why aren't they ordered by id, and to avoid that you need to do something like Comment.unscoped.order(:id)
which is annoying if you ask me, instead i would prefer doing a scope that i could invoke only when i know i need it
scope :chronological_order -> { order(created_at: :desc) }
Then call it
Comment.chronological_order
of course you can pick whatever scope name you prefer.
Upvotes: 0
Reputation: 115541
In your Comment model, add:
default_scope -> { order('created_at DESC') }
This way, @post.comments
will be properly ordered.
Upvotes: 1