Over a million developers have joined DZone.

Simple Conversion Of Rails Will_paginate To Ajax

This, by default, converts will_paginate links to Ajax links using unobtrusive Javascript. It uses Prototype and assumes the container to be refreshed has an id of 'pagination_container', but this can be overridden. It is a modified version of Andrea Franz' code, written for the same purpose. The modifications allow one to use the code to turn any link into an Ajax call.

Place the following in application.js

var UnobtrusiveLinker = Class.create({ 

  initialize: function() {
    this.options = Object.extend({
      container: 'pagination_container',
      selector: 'div.pagination a'
    }, arguments[0] || {});

  initLinks: function() {
    $(this.options.container).select(this.options.selector).invoke('observe', 'click', this.linkHandler.bind(this));

  linkHandler: function(event) {
    new Ajax.Updater(this.options.container, event.element().getAttribute('href'),{
      method: 'get',
      onComplete: this.initLinks.bind(this)


To convert will_paginate to Ajax, simply embed the following in the applicable page:

But, it is easier to use a helper in application_helper.rb:

  def make_links_ajax(opts = [{}])
    opts = [opts] if opts.is_a? Hash
    ret = "document.observe('dom:loaded', function() { "
    opts.each {|option| ret += "new UnobtrusiveLinker(#{option.to_json}); "}
    ret + "});\n"

Which allows this for the default case:

<%= javascript_tag(make_links_ajax()) %>

Or the following if you want to specify the container and selector, or specify more than one:

<%= javascript_tag(make_links_ajax(:container => 'my_container', :selector => 'a.my_links')) %>

<%= javascript_tag( make_links_ajax([{:container => 'pagination_container', :selector => 'div.pagination a'}, {:container => 'another_container', :selector => 'a.another_link_class'}]) ) %>


{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}