user646560
user646560

Reputation:

Ruby on Rails: Display objects by most recent in the view?

I have this method at the moment:

  <% for comment in @critical_process.review.comments %>
      <div id="comment">
        <%=h comment.comment %> <br/>
        <span id="comment_email">
        By: <%=h comment.user.email%>
        </span>
      </div>
  <% end %>

however I need it to display the comments in order of the most recently updated at the top and work its way down.

Thanks

Upvotes: 4

Views: 5456

Answers (1)

npad
npad

Reputation: 5046

Assuming the Comment model has an updated_at column, and you are using Rails 3, you can just tell ActiveRecord to order the Comment records appropriately as follows:

<% for comment in @critical_process.review.comments.order('updated_at DESC') %>

The Rails 2.x equivalent would be:

<% for comment in @critical_process.review.comments.all(:order => 'updated_at DESC') %>

Whilst this will work perfectly well, it's generally considered best to move most of your query generation into the controller, in which case you might do the following in the controller:

@comments = @critical_process.review.comments.order('updated_at DESC')

... and then iterate over the @comments collection in the view.

Upvotes: 8

Related Questions