Rails alphabetical pagination

A common problem we often run into at eden is paginating a list of things alphabetically. I thought it was possible with will_paginate but apparently not, so yesterday we created our own simple solution, and today we rolled it into a plugin.

Here’s a little tutorial of how to use it.

So i have a nice simple view of Gowalla pins ordered by name. Please forgive the scaffolding! ;)

Gowalla pins

This page is quite long. Of course, we could use standard pagination to make it 10 per page or something, but it wouldn’t be very helpful if you were looking for a pin with a particular name. You’d have to click through the pages to find it. Wouldn’t it be neat to list a page for each letter?

Enter paginate_alphabetically!

Simply install it as a plugin:

rails plugin install http://github.com/edendevelopment/paginate_alphabetically.git

Enable pagination in the model:

class Pin < ActiveRecord::Base
  paginate_alphabetically :by => :name

Make the controller fetch the right pins:

class PinsController < ApplicationController
  def index
    @pins = Pin.alphabetical_group(params[:letter])

Add pagination links in the view:

<ul class='pagination'>
  <strong>Jump to:</strong>
  <%- Pin.pagination_letters.each do |letter| -%>
    <li><%= link_to(letter, pins_path(:letter => letter)) %></li>
  <%- end -%>

Perhaps a touch of CSS:

ul.pagination {
  list-style: none;
  color: lightgray;
  padding: 1em 0.5em;

ul.pagination strong {
  color: black;

ul.pagination li {
  display: inline;
  font-size: 1.1em;

ul.pagination li:before {
  content: '| ';

And here it is:

Gowalla pins beginning with E

The cool thing is you can add this to any of your models, and paginate by any attribute you wish.

Tested with Rails 2.3.5 and Rails 3 release candidate.

Get it from github: http://github.com/edendevelopment/paginate_alphabetically
or RubyGems: http://rubygems.org/gems/paginate_alphabetically

Thanks to Tom, Enrique and tooky for their help making this.


4 comments on “Rails alphabetical pagination

  1. Pingback: Alphabetical Pagination, version 0.2.3 « aimee daniells

  2. this doesn’t work at all… I tried to install in gem and plugin but they both failed with a message: undefined method `alphabetically_paginate

    • Oh dear, shame, sorry about that. One day i might look at it again, but it’s not a priority for me right now. If you find a solution, feel free to send me a pull request.

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 )

Google+ photo

You are commenting using your Google+ 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 )


Connecting to %s