When you have a partial in
/app/views/posts/comments/_comment.html.erb,
doing the following
<%= render @post.comments %>
iterates the @post.comments collection like
@post.comments.each do |comment|
automatically, even if you don’t pass in the collection into the partial.
However, this will render the comments in the other direction, because of the way objects are sorted by created_at.
I want to change the direction: sort the collection in the other way by created_at DESC, and then iterate the comments collection.
I would do
@comments = @post.comments.paginate(:page => params[:page], :per_page => 10, :order => "created_at") in the PostsContoller and <%= render @comments %> instead of <%= @post.comments %>, but I was curious if there were any more common way of doing this.
Thanks in advance!
You definitely want to do:
instead of changing how a Rails helper works! Why would you do that?
You can define how comments are ordered on the association. In the Post model:
You can also set a default scope to change how the comments are ordered by default.
In the model: