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 に答える