Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Simple Search with Kaminari Pagination Gem

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.

like image 201
Aaron Avatar asked Jan 15 '23 22:01

Aaron


1 Answers

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

like image 173
Santosh Avatar answered Jan 21 '23 18:01

Santosh