Topic: Paginating search results with will_paginate

Followed the excellent Railscasts on will_paginate and Simple Search Form and now I'd like to paginate my search results.

Anyone got a tip for a noob on the best way to paginate the results of a simple search like the one Ryan describes?

Specifically I'm looking to paginate a list of machines.

machine.rb

def self.search(search)
  if search
    find(:all, :conditions => ['name LIKE ?', "%#{search}%"])
  else
    find(:all)
  end
end


machines_controller.rb

def list
  if params[:search]
    @machines = Machine.search(params[:search])
  else
    @machines = Machine.paginate :all, :per_page => 5, :page => params[:page], :order => 'name'
  end
end

Re: Paginating search results with will_paginate

The "paginate" method is a replacement for the "find" method. Try this:

# models/machine.rb
def self.search(search, page)
  conditions = nil
  unless search.blank?
    conditions = ['name like ?', "%#{search}%"]
  end
  paginate :per_page => 5, :page => page, :conditions => conditions, :order => 'name'
end

# machines_controller.rb
def index
  @machines = Machine.search(params[:search], params[:page])
end

Railscasts - Free Ruby on Rails Screencasts

Re: Paginating search results with will_paginate

Thanks AGAIN Ryan.

You're a tribute to your kind. I've learned more from your Railscasts, direct replies to my posts and reading your other posts than from any other source, bar none. It is greatly appreciated.

One day I hope to know enough of what I'm doing to help the next noob in line :-)