Rails WillPaginate::Collection not paginating Array

一笑奈何 提交于 2019-12-23 04:08:42

问题


An existing array vparray is being generated, then sorted by a non-db column rate. It then needs to be paginated :

    @vps  = vparray.sort_by{|e| e.rate}
    @vps = WillPaginate::Collection.create(1, 10, @vps.length) do |pager|
      pager.replace @vps
    end

The view;

<%= will_paginate @vps, :previous_label => "prev ", :next_label => " next" -%>

renders fine, the number of pages pans out and the page is apparently the first. However, upon: <% @vps.each do |product| %>, the entire sorted array is being rendered.

Apparently, the array can only be populated with values of current page. However

   @vps  = vparray.sort_by{|e| e.rate}
   @vps = @vps.paginate(:page => params[:page], :per_page => 10)
   @vps = WillPaginate::Collection.create(1, 10, @vps.length) do |pager|
      pager.replace @vps
    end

is incorrect. The paginate command actually reduces the found set to the same number as per_page and therefore == only 1 page!

So I'm assuming that line should not be there. The view should be calling the proper page of results

<% @vps.each do |product| %>

something better than

<% @vps.page(params[:page]).each do |product| %>

that generates undefined methodpage for WillPaginate::Collection`

context: ruby 1.9.3, rails 3.2.17, will_paginate 3.0.5


回答1:


Went and re-read the collection.rb and array.rb libraries.

With controller stating:

require "will_paginate/array"

@vgps  = vgp.sort_by{|e| e.rate}
@vgps = @vgps.paginate(:page => params[:page], :per_page => 30)

This is all that is necessary for a sorted array.



来源:https://stackoverflow.com/questions/23875093/rails-willpaginatecollection-not-paginating-array

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!