Rails pagination with N results

For a site I’m building with Rails, I wanted to paginate the results of a database query with the built in pagination utilities. However, out of the box, paginate doesn’t take a :limit option, because that’s used to get a certain number of results per page. This is the workaround I put together. Perhaps there are better ways, but this was quick and efficient.

In the controller:

class StoreController < ApplicationController

   # This is for Pagination.
   DEFAULT_OPTIONS[:first_n] = nil

This lets you use a new option to paginate, :first_n (which isn’t the best name, but was the first thing that popped into my head).

Now, you override this method:

  def count_collection_for_pagination(model, options)
    unless options[:first_n].nil?
      return options[:first_n]
    else
      return model.count(:conditions => options[:conditions],
                         :joins => options[:join] || options[:joins],
                         :include => options[:include],
                         :select => options[:count])
    end
  end

So, if you only want N results, you then do:

@prod_pages, @products = paginate(:products, :condition => condition, :first_n => 100)

Seems to be pretty quick and simple, so it works for me, although I’m sure a Ruby expert could make it look even nicer.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s