Paginate the results of a query in Ruby on Rails

Posted on 12 May 2006

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

Paul works for Kyan web design agency in Surrey, UK as a Ruby on Rails developer.

Follow Paul on Twitter

Email: paulsturgess [at] gmail.com

Read more articles in the archive →

Comments...

  • 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.

    Chris B at 30 Jan 08 at 14:25

Got something to say?