0

我有 2 个课程:PostsComments,其中帖子has_many :commentscomments belongs_to post.

我的每个帖子都有一个带有评论列表的显示页面,我想对评论进行分页。使用我拥有的当前代码,我将显示所有页面上所有评论的列表。所以,如果我有 10 条评论,并且我想在每页上有 2 条评论,我会得到 5 页,上面有原始的 10 条评论。有人可以解释一下吗?

我的代码:

Posts controller:

def show
  @post = Post.find(params[:id])
  @comments = @post.comments.page(params[:page]).per(3)

  respond_to do |format|
    format.html # show.html.erb
   format.json { render json: @post }
  end
end


"Show" views:

<%= paginate @comments %>

<% @post.comments.each_with_index do |comments, index| %>
    <tr>
    <td><%= index+1 %></td>
    <td><%= comment.date %></td>
    <td><%= comment.text %></td>
  </tr>
  <% end %>
</table>
4

1 回答 1

1

您需要在视图中使用分页对象,而不是从数据库中获取它们:

<% @comments.each_with_index do |comments, index| %>
  <tr>
    <td><%= index+1 %></td>
    <td><%= comment.date %></td>
    <td><%= comment.text %></td>
  </tr>
<% end %>

这使它们新鲜,未分页:

@post.comments
于 2013-05-31T19:33:38.217 回答