4

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.

Aaron
  • 143
  • 3
  • 10

1 Answers1

9

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

Santosh
  • 1,251
  • 9
  • 15
  • It would be a better answer if it had the explanation... "Give a man a fish and you feed him for a day. Teach a man to fish and you feed him for a lifetime." – Agush Nov 23 '12 at 23:02
  • @Aaron I just updated my answer more descriptive as suggested by Agush – Santosh Nov 24 '12 at 05:22
  • 1
    @Santosh I accepted the answer, but could not upvote it due to lack of reputations. Thanks for the detailed explanation...I appreciate knowing the reason and not just the solution. – Aaron Nov 27 '12 at 03:24
  • 1
    In Rails 4 you'd use a "where" clause instead of "find". Where will return a scope, so you won't have to differentiate between Array and Scope. – Amin Ariana May 05 '14 at 21:01