kaminari undefined method 'page'
Asked Answered
O

3

5

I am trying to add Kaminari to my Rails app. I have included the gem and this is what my controller looks like:

def index
    if params[:year]
      if params[:year].size > 0
        @songs = Song.where("year like ?", params[:year]).page(params[:page])
      elsif params[:artist].size > 0
        @songs = Song.where("artist_name like ?", params[:artist]).page(params[:page])
      elsif params[:song].size > 0
        @songs = Song.where("title like ?", params[:song]).page(params[:page])
      end
    else
      @songs = Song.first(10).page(params[:page])
    end
  end

and then adding

<%= paginate @songs %>

in my view, the error I am getting is:

undefined method `page' for #<Array:0x007fab0455b4a8>

Not sure why this is coming up as I followed the docs step for step.

Orlando answered 30/1, 2014 at 18:11 Comment(0)
A
19

Kaminari uses paginate_array to paginate an array. 2 solutions:

First, you can use limit(10) instead of first(10):

@songs = Song.limit(10).page(params[:page])

Second, use paginate_array

@songs = Kaminari.paginate_array(Song.first(10)).page(params[:page])

Amoebaean answered 30/1, 2014 at 18:27 Comment(1)
The way this is structured concerns me: does paginate_array operate on an already resolved query?Hendershot
S
2

I'd advise you rewrite your controller slightly. Better yet, move your filters to the model or a filter class. Look into present? for testing existence of params as that will check for nil and empty.

def index
  @songs = Song

  @songs = @songs.where("year like ?", params[:year])          if params[:year]
  @songs = @songs.where("artist_name like ?", params[:artist]) if params[:artist]
  @songs = @songs.where("title like ?", params[:song])         if params[:song]

  @songs = @songs.limit(10).page(params[:page])
end
Stake answered 30/1, 2014 at 18:56 Comment(0)
T
0

Tl;DR If you use Mongoid, use kaminari-mongoid instead of kaminari alone.

At Github it said, Kaminari supports Mongoid...so I went and installed gem 'kaminari' with the result: unknown method :page...later i found the mongoid adapter: kaminari-mongoid and that works now.

Takao answered 13/5, 2020 at 16:15 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.