Using Simple Search Using Kaminari Pagination Gem

I am trying to apply pagination on my rails application using Kaminari. I also include a simple search form based on Railscast Episode # 37 . When I try to apply the kaminari page and for each method, 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 delete the pagination, the search works fine. When I delete the search, pagination works fine. I just can't use both of them and correctly execute the code function. Please let me know if there is something in my code that I am missing that makes it work incorrectly.

+4
source share
1 answer

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

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

Add a check to 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

+9
source

Source: https://habr.com/ru/post/1448002/


All Articles