rails pagination – 后续页面中的不同per_page值第1页

我有一个博客/维基应用程序,我希望主页包含欢迎/登陆消息和5个最新的博客条目和链接到旧条目的分页。

例如,是否可以将5页作为分页搜索结果的第1页返回,将15页作为后续页面返回? 我目前正在使用will_paginate。

您可以使用WillPaginate::Collection ,以下是您可以使用的示例:

 def self.find_with_pagination(params = {}) WillPaginate::Collection.create(params[:page].to_i < 1 ? 1 : params[:page], per_page_for_page(params[:page])) do |pager| # inject the result array into the paginated collection: pager.replace(find(:all, params.merge({:limit => pager.per_page, :offset => pager.offset)})) unless pager.total_entries # the pager didn't manage to guess the total count, do it manually pager.total_entries = self.count end end end def self.offset_for_page(page_number) page_number.to_i > 1 ? ((page_number.to_i - 2) * 15 + 5) : 0 end def self.per_page_for_page(page_number) page_number.to_i > 1 ? 15 : 5 end 

我希望它会有所帮助,这里是doc的链接: http : //rdoc.info/github/mislav/will_paginate/master/WillPaginate/Collection

对我而言,听起来你有两个截然不同的观点,你想要合并为一个:“欢迎”和“档案”。 将一个页面拆分为两个可能更简单:

  • “欢迎”页面,显示欢迎信息,最新的Xpost以及“旧post”的链接。
  • 包含所有post的“档案”页面将根据需要进行will_paginate 。 是的,前五个post也会出现在这里,但这在档案中是预期的(也可能是好的)。

只是一种不同的思考方式 – 希望它有所帮助!

我没有试过这个,但也许通过覆盖后续页面上的params [:per_page]将会起作用。 就像是:

由于控制器是这样的:

  @posts = Post.paginate :page => params[:page], :per_page => 10, :include => [:posts], :conditions => ["post.user_id = ?", current_user.id], :order => "title,created_at" 

视图也许可能有这样的东西:

 <%= params[:page] == 1 ? will_paginate @posts : will_paginate @posts, :per_page => 15 %> 

是的,答案有点旧,但我会在这里给出我在Rails 4.2上的解决方案,因为它有点不同。

我在第一页需要10个结果,在其他页面需要12个结果。

item.rb的

 def self.find_with_pagination(params = {}, filters = {}) WillPaginate::Collection.create(params[:page].to_i < 1 ? 1 : params[:page], per_page_for_page(params[:page])) do |pager| result = Item.all.limit(pager.per_page).offset(offset_for_page(params[:page])).where(filters) pager.replace result unless pager.total_entries # the pager didn't manage to guess the total count, do it manually pager.total_entries = self.count end end end def self.offset_for_page(page_number) page_number.to_i > 1 ? ((page_number.to_i - 2) * 12 + 10) : 0 end def self.per_page_for_page(page_number) page_number.to_i > 1 ? 12 : 10 end 

your_super_controller.rb

 @items = Item.find_with_pagination(params, @filters)