Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

Simple Conversion Of Rails Will_paginate To Ajax

DZone's Guide to

Simple Conversion Of Rails Will_paginate To Ajax

·
Free Resource
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] || {});
    this.initLinks();
  },  

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

  linkHandler: function(event) {
    event.stop();
    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"
  end


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'}]) ) %>

Topics:

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}