2013-05-31 173 views
0

我有2个类:PostsComments,其中帖子has_many :commentscomments belongs_to postRails kaminari分页子表

我的每篇文章都有一个带有评论列表的显示页面,我想分页评论。使用当前的代码,我将显示所有页面上的所有评论列表。所以,如果我有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> 

回答

1

您需要使用分页对象的视图,而不是让他们从数据库中新鲜:

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

这让他们新鲜,unpaginated:

@post.comments 
+0

页面现在正确显示。但是,每次移至下一页时,我的索引都会重置。有没有办法保持评论运行指数,尽管他们在哪个页面?例如第1页有指数1-5,2有6-10?谢谢。 – Mozbi