will_paginate & filterrific: undefined method `total_pages' for #<Array:0x007f9f6b4a3320>

1.5k views Asked by At

I'm trying to use will_paginate in conjunction with filterrific. But I'm getting the following error:

undefined method `total_pages' for # Array:0x007f9f6b4a3320>

My controller action:

  def index
    @filterrific = initialize_filterrific(
      current_user.assessments,
      params[:filterrific],
      :select_options => {
        sorted_by: Assessment.options_for_sorted_by      },
        :persistence_id => false,
    ) or return
    @assessments = @filterrific.find.page(params[:page]).paginate(page: params[:page], per_page: 10).sort_by &:created_at
    @assessments.reverse!
  end

View:

<%= render(
  partial: 'list',
  locals: { assessments: @assessments }
) %>

</div>

Partial:

<div id="filterrific_results">



    <% @assessments.each do |assessment| %>
    ....
    <% end %>

</div>


<%= will_paginate assessments %>

Where am I going wrong?

3

There are 3 answers

0
dileep nandanam On

Avoid calling sort_by over paginated collection. Add scope to Assessments and specify the scope for filterrific.

asessment.rb
class Assessment < ActiveRecord::Base
    filterrific(
      available_filters: [
        :oldest_first
      ]
    )
    scope :oldest_first, lambda { order('created_at ASC') }
0
Jo Hund On

The issue is that you are casting an ActiveRecord collection proxy to an array with the following two methods:

  • .sort_by
  • .reverse

Make sure to set the order using an ActiveRecord method. This should work: .order('created_at DESC').

You are also calling the pagination method twice: .page and .paginate. Once should be enough.

0
Aster On

This is because you're calling both ".page" and ".paginate". I'm ok with below code. I know you already solved this because the question is posted last two years but I'm just sharing my experience for friend who will face with this issue in later.

    @filterrific.find.page(params[:page]).per_page(10)