Ruby on Rails: Show the latest objects in a 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 the order of the last updated at the top and work its way down.

thanks

+4
source share
1 answer

Assuming the comment model has an updated_at column, and you are using Rails 3, you can simply tell ActiveRecord to order comment entries as follows:

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

Rails 2.x equivalent:

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

Although this will work fine, it is usually best to move most of your request to the controller, in which case you can do the following in the controller:

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

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

+7
source

Source: https://habr.com/ru/post/1346591/


All Articles