Paginate the results of a query in Ruby on Rails
To paginate the results of a query you need to use conditions. Which can easily be combined into the default pagination built into Rails.
So you can do:
@query = params[:query].strip
@track_pages, @tracks = paginate(:tracks, :per_page => 10, :conditions => [ "tracks.`name` LIKE ?", "%#{@query}%"])
If you would like to query more than one table you just use :include like so:
@track_pages, @tracks = paginate(:tracks, :per_page => 20,
:include => :artist,
:conditions => [ "tracks.`name` LIKE ? or artists.`name` LIKE ?", "%#{@query}%", "%#{@query}%"])
About
Paul is a web developer for Kyanmedia web agency. He's lucky enough to write in Ruby on Rails full-time and uses this site to post snippets of code.
Contact
my name at gmail.com
More snippets
Take a look in the archive
Need a website?
Contact my employer. Make sure to check out our portfolio of work.
Hosting
I recommend hostingrails.com
1 comment made
I can’t believe it! I keep going down the list and keep finding more things that I’ve been trying to figure out for the past couple of weeks.
Got something to say?