Using Simple Search with Kaminari Pagination Gem

kaminari, ruby-on-rails, search

Solution

In your case, you are returning array object from the search method not ActiveRecord::Relation object.

 find(:all, conditions: ...) # find method will return an array object.

Add check in your controller,

def index
  @posts = Post.search(params[:search])
  if @posts.class == Array
    @posts = Kaminari.paginate_array(@posts).page(params[:page]).per(10) 
  else
    @posts = @posts.page(params[:page]).per(10) # if @posts is AR::Relation object 
  end
end

Kaminari pagination with an array https://github.com/amatsuda/kaminari#paginating-a-generic-array-object

for ActiveRecord::Relation object, checkout this http://railscasts.com/episodes/239-activerecord-relation-walkthrough

Problem

I am trying to apply pagination to my rails app using Kaminari. I am also incorporating a simple search form based on the Railscast Episode #37. When I try to apply the kaminari page and per methods I get the error 'undefined method page'. Below is the code I'm using. posts_controller.rb ``` def index @posts = Post.search(params[:search]).page(params[:page]).per(2) end ``` post.rb ``` def self.search(search) if search find(:all, conditions: ['title || body LIKE ?', "%#{search}%"], order: "created_at DESC") else find(:all) end end ``` index.html.erb ``` <%= paginate @posts %> ``` When I remove the pagination the search works fine. When I remove the search the pagination works fine. I just can't seem to use them both and have the code function properly. Please advise if there is something in my code that I am missing that is causing this not to work properly.

Original source