zerosum dirt(nap)

evolution through a series of accidents

zerosum dirt(nap)

Paginating Associations

April 10, 2007 by nap · Comments

It’s no real secret that the default Rails pagination helpers are kind of awful. Sure, you can use them, but I wouldn’t recommend it if you expect to scale. Instead, go snag yourself the wonderful paginating_find plugin. And then, if you’re going to be using them with your model associations, whip up an association extension like this:

module PaginationExtension
  def paginate(current = 1, size = 10, options = {})
    options[:page] = {:current => current, :size => size}
    find(:all, options)
  end
end

Now just extend the has_many association on your City class and you can call city.bars.paginate(2) to get the second 10-element page of bars associated with your city.

class City < ActiveRecord::Base
  has_many :bars, :extend => PaginationExtension
end

city.bars.paginate(2)

The good bars are all on the first page though, so consider yourself warned.

blog comments powered by Disqus