eddorre

Tutorial: Filtering results with jQuery UI Slider and Rails


At Planet Argon, we’re using the jQuery UI slider to filter results on one of our client projects. Since I had never implemented anything with jQuery UI slider, I decided to whip up a quick prototype just to see how it worked. It took me a little under an hour to get something put together. This post is the result of that prototype.

First of all, let’s visualize what we want to achieve. In my example, I have 20 dummy stocks that I want to filter down based on a high and low price. Here is a sample screen shot:

stocks

We’re going to start from scratch from a brand new Rails project. So we’ll have to create it:

NOTE: This tutorial uses Rails 2.3.4 but it can be easily adapted to work with recent earlier versions.

rails jquery_slider_rails

Since we’re using jQuery instead of Prototype, we’ll want to install the jRails gem. While we’re installing gems, we’ll install a gem called Faker to create some dummy names.

sudo gem install aaronchi-jrails --version=0.5.1
sudo gem install faker

In order to use them, we’ll have to add config.gem statements to our environment.rb file.

  config.gem "faker"
  config.gem "aaronchi-jrails", :lib => false, :version => "0.5.1"

Next thing we’ll have to do is go to the jQuery UI download page and we’ll download a custom build of jQuery UI. For this example, we’ll go lightweight and just select UI core and slider. I chose UI Lightness as the theme, but you can choose whatever you like; the theme won’t impact the results.

Once you download the files, place them in the following locations:

  • Images
    • /public/images/
  • jQuery and jQuery UI Javascript files
    • /public/javascripts/
  • CSS file
    • /public/stylesheets/

Now that we have all of the supporting files that we’ll need we’re ready to create our model that holds Stock information.

NOTE: Although I’m creating RSpec models and controller, I’m not writing any specs for this simple app. Perhaps that’s a post for another day.

script/generate rspec_model stock name:string price:integer

It’s probably a good idea to add an index on the price attribute since we’re going to be filtering on it.

Open up the db/migration directory and edit the only migration file to add the index. It should look like this when we’re done:

class CreateStocks < ActiveRecord::Migration
  def self.up
    create_table :stocks do |t|
      t.string :name
      t.integer :price
      t.timestamps
      
      t.index :price
    end
  end

  def self.down
    drop_table :stocks
  end
end

Now that we have the migration, we’re ready to create our database and run said migration:

rake db:create:all
rake db:migrate

We should have a running database now (on SQLite) but now we need some data. We’ll mis(use) the seed file functionality that was added in Rails 2.3.4. You can find the seeds.rb file in the db directory.

We want 20 dummy stocks with fake names and fake prices. For fake random names, we’ll use the Faker gem. The Faker gem comes in really handy for writing specs/tests. A topic that I’ll probably cover soon. For random prices, we’ll just use Ruby’s rand method.

20.times do |x|
  Stock.create(:name => Faker::Lorem.words(1).to_s, :price => rand(5 * (100)))
end

Once we save the file, we can load up our data by running the following command:

rake db:seed

Once the sample data has been seeded we can start building our model. We know that we want to filter the data based on two points on the slider. This can easily by done by a named scope that takes two arguments.

named_scope :filter, lambda { |low, high| { :conditions => { :price => low..high } } }

We’ll also need to grab the highest and lowest prices to plug in as max and min values into the slider. For that we can create a class method that returns each price in an array.

  def self.high_low_prices
    [Stock.minimum(:price), Stock.maximum(:price)]
  end

Let’s move over to our controller. We know that we’ll need an index action but we’ll also need some sort of action to respond to slider ‘stop’ events. We can easily create a filter method/action in the controller, but as it turns out we can actually re-use the index action and remain fully RESTful.

Let’s focus on getting the correct data. We’ll be passing in the two points from the slider as parameters. If both of those exist, we’ll actually call our filter named scope. If not, we’ll just grab all of the stocks.

    unless params[:low] && params[:high]
      @stocks = Stock.all
    else
      @stocks = Stock.filter(params[:low], params[:high])
    end

We can probably grab the highest and lowest stock prices from the stocks instance variable, but let’s be explicit.

@price_range = Stock.high_low_prices

If the request is not an ajax request we’ll load the index view. If it’s an ajax request, let’s replace our stock list with the filtered list.

    respond_to do |format|
      format.html
      format.js do
        render :update do |page|
          page.replace_html 'x_stock_list', :partial => 'stocks/stock_list', :locals => { :stocks => @stocks }
        end
      end
    end
  end

We can use the replace_html method here because we’re using the jRails gem.

We’re now ready to tackle the views.

Create an index.html.erb view under /app/views/stocks/. While we’re at it we’ll create the partial that we alluded to in our controller. We’ll call this _stock_list.html.erb and it goes into the same directory as the index view.

Add the boilerplate stuff to the index.html.erb view; a DOCTYPE, html, head, and body tags. I also added an h1 tag wrapping the word Stocks.

Remember those jQuery files that we downloaded a while ago? We’ll link to them now.

  <head>
    <%= stylesheet_link_tag 'jquery-ui-1.7.2.custom.css' %>
    <%= javascript_include_tag 'jquery-1.3.2.min.js', 'jquery-ui-1.7.2.custom.min.js' %>
  </head>

Inside the body tag, we’ll create a div so that our slider can hook into it. NOTE: I use inline styles here because this is a quick and dirty example. Please keep all styles in CSS files in a real app.

I also have gotten in the habit of prepending all classes and IDs that are used by Javascript and ajax interactions with ‘x_’. This is a convention that we use at Planet Argon. Robby Russell originally blogged about this in the article Designers, Developers, and the x_ Factor

    <div id="x_slider" style="font-size:62.5%; width:350px;"></div>

I follow the slider div another div for the high and low prices.

     <div>
       <p>Showing all stocks between <span id="x_low_selected"><%= @price_range.first %></span> and <span id="x_high_selected"><%= @price_range.last %></span></p>
     </div>

The last HTML elements on the page is the stock list itself.

    <ul id="x_stock_list">
      <%= render 'stock_list', :stocks => @stocks %>
    </ul>

Before we get to the jQuery code, let’s jump over to our partial and flesh it out. The code necessary is minimal.

<% @stocks.each do |stock| %>
  <li>
      <p><%= stock.name %></p>
      <p><%= stock.price %></p>
  </li>
<% end  %>

The jQuery UI slider library takes care of most of the heavy lifting. Here is the final slider Javascript code with an explanation below it of all of the settings.

    <script type="text/javascript">
      $(function() {
        $("#x_slider").slider( { 
          range: true,
          step: 10,
          max: <%= @price_range.last %>,
          min: <%= @price_range.first %>,
          values: [<%= @price_range.first %>, <%= @price_range.last %> ],
          stop: function(event, ui) {
            var prices = $('#x_slider').slider('option', 'values');
            $('#x_low_selected').html(prices[0]);
            $('#x_high_selected').html(prices[1]);
            $.ajax({
              type: "GET",
              data: ({ low: prices[0], high: prices[1] }),
              url: 'http://0.0.0.0:3000/stocks',
              dataType: 'script'
            });
          }
        });
      });
    </script>

Before we bind the slider to our div, we’ll wrap everything in a convenience function to make sure that the DOM is loaded.

Next we bind the slider by simply writing:

$("x_slider").slider( { options here }

As you can see in the code above, the slider takes several options (see full documentation for all options):

  • Range
    • When this is set to true, you’ll get two or more points on the slider
    • Step
    • This is the value that the slider decrements or increments every time you move a point
  • Max
    • The maximum value of the slider
  • Min
    • The minimum value of the slider
  • Values
    • An array of low and high points on the slider
  • Stop
    • This is an event that is fired when a point on the slider stops moving

In the stop event there is a bunch of stuff going on. First, I set a price array to the set points on the slider so I can use them later for updating the user of the min and max values as well as passing those in as parameters to the ajax call.

This code snippet simply replaces the min and max values on the page:

$('#x_low_selected').html(prices[0]);
$('#x_high_selected').html(prices[1]);

The ajax function also has several options:

  • Type
    • This is the type of HTTP request. A simple GET request will do here
  • Data
    • These are the variables that we’ll be sending along
  • URL
    • This is the URL that we’ll be hitting – this assumes that you’ve started the web server using script/server or mongrel_rails
  • DataType
    • I originally set this to html thinking that is what I wanted, but that’s the wrong call. You’ll want to use script if you want to return fragments of HTML otherwise you’ll return the whole page in HTML form (layout and all).

That’s it. As I said before, to test it, you’ll want to start up a web server with either mongrel_rails, script/server or Passenger. In your web browser, you should be able to go to either http://0.0.0.0:3000/stocks or http://jquery_slider_rails.local/stocks if you’re using Passenger to see the results.

I’ve made all of the code available for this tutorial on GitHub.


Add Your Comment





(Preview)

end kanji