Ruby on Rails: 在视图中按最新显示对象?

4
我目前有这个方法:

现在我有这个方法:

  <% 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 %>

然而,我需要它按照最近更新的顺序显示评论,并从上到下运行。

谢谢

1个回答

8
假设评论模型有一个updated_at列,并且您正在使用Rails 3,则可以告诉ActiveRecord按照以下方式适当地排序评论记录:
<% for comment in @critical_process.review.comments.order('updated_at DESC') %>

相当于Rails 2.x:

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

虽然这样做完全可行,但通常最好将大多数查询生成放入控制器中。在这种情况下,您可以在控制器中执行以下操作:

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

然后在视图中迭代@comments集合。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接