0

我的应用程序中有以下代码创建一个表:

<% @comments.each do |comment| %>
        <td>
        <%= link_to (comment.body), comment.pin %>
        </td>

        <td>
        <%= time_ago_in_words(comment.created_at) %> ago</br>
        </td>

        <td>
        <%= link_to (comment.pin.user.name), comment.pin.user %>
        </td>

        <td>
        <%= comment.pin.album %>
        </td>

        <td>
        <%= comment.pin.artist %>
        </td>

这是我的评论控制器:

def create
@pin = Pin.find(params[:pin_id])
@comment = @pin.comments.create(params[:comment])
@comment.user = current_user

respond_to do |format|
  if @comment.save
    format.html { redirect_to @pin, notice: 'Comment was successfully created.' }
    format.json { render json: @comment, status: :created, location: @comment }
  else
    format.html { render action: "new" }
    format.json { render json: @comment.errors, status: :unprocessable_entity }
  end
end

结尾

它工作得很好,除了它将每个新评论添加到表格底部。如何以相反的顺序显示它,以便最先显示最新的评论?另外,我怎么能把它限制在最近的 50 条评论中?

4

1 回答 1

0

我猜想在你的控制器动作中你正在做这样的事情:

@comments = @post.comments

这将以默认顺序(或随机,取决于数据库)加载所有帖子。将上面的内容调整为这样的:

@comments = @post.comments.order('created_at DESC').limit(50)

您还可以为订单创建范围并限制 DRY 事情。

于 2013-09-10T23:26:01.773 回答