Kaminari installed but apparently not seen

85 Views Asked by At

A rails test is generating an error as follows

ActionView::Template::Error: undefined method `total_pages' for nil:NilClass

        options[:total_pages] ||= scope.total_pages

for this specific line in the view: <%= paginate @carts %>
The controller action generates an empty array according to the following logic

    if user?
      @carts = Cart.order(created_at: :desc).where([user_id = ?, current_user.id]).page params[:page]
    else
      @carts = []
    end

Kaminari is bundled

Using kaminari-core 1.2.2
Using kaminari-actionview 1.2.2
Using kaminari-activerecord 1.2.2
Using kaminari 1.2.2

a puts @carts.size does show 0 in the logging. so the array object exists but the scoping is not activating. It appears the base settings of kaminari are not kicking in in this particular instance, whereas in another case @users = User.page params[:page] the test does not complain.

How does this get resolved?

1

There are 1 best solutions below

0
Alex On
paginate []     # undefined method `total_pages' for []:Array
paginate nil    # undefined method `total_pages' for nil:NilClass
#        ^                                           ^
# NOTE: from the error it looks like @carts is nil --'

kaminari needs an ActiveRecord class or relation object and page method has to be called on that class/object for it to become "paginatable" and for scoping to kick in:

paginate Cart             # => undefined method `total_pages' for Cart:Class
paginate Cart.all         # => undefined method `total_pages' for #<ActiveRecord::Rel...

paginate Cart.page(1)     # => <nav class="pagination" ...
paginate Cart.all.page(1) # => <nav class="pagination" ...

Kaminari has a helper to paginate over an array:

@array = Kaminari.paginate_array([1,2,3]).page(1).per(10)

paginate @array           # => <nav class="pagination" ...

An empty Cart relation object can also be used:

paginate Cart.none.page   # => ""

https://github.com/kaminari/kaminari#paginating-a-generic-array-object