正如上述评论者之一所提到的,我建议使用 will paginate gem。
然后你会像这样实现它(这些是 gem 页面中的示例......):
## perform a paginated query:
@posts = Post.paginate(:page => params[:page])
# or, use an explicit "per page" limit:
Post.paginate(:page => params[:page], :per_page => 30)
## render page links in the view:
<%= will_paginate @posts %>
在您的具体示例中,它将是这样的:
def index
@posts = Post.paginate(:page => params[:page])
respond_to do |format|
format.html # index.html.erb
format.json { render :json => @posts }
end
end
你的观点会更简单:
<%= will_paginate @posts %>
您需要处理一些细节,但这会使事情变得容易得多。
这里有 2 个 Railscasts 可以给你一些背景知识:
http://railscasts.com/episodes/174-pagination-with-ajax/
http://railscasts.com/episodes/240-search-sort-paginate-with-ajax