Put Flexigrid on Rails

Would you like a free, beautiful, lightweight and feature-rich grid control for all of your Rails applications? Then it is time to put Flexigrid on Rails.

Step 1: Download the necessary files

To run this example, you will need the following files:

Step 2: Create the Rails application


rails Flexigrid

Step 3: Create the Controller and Model


ruby script/generate Controller Countries
ruby script/generate Model Country


Step 4: Configure the database connection

Open config/database.yml and paste the following:


  # MySQL.  Versions 4.1 and 5.0 are recommended.
  #
  # Install the MySQL driver:
  #   gem install mysql
  # On Mac OS X:
  #   sudo gem install mysql -- --with-mysql-dir=/usr/local/mysql
  # On Mac OS X Leopard:
  #   sudo env ARCHFLAGS="-arch i386" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config
  #       This sets the ARCHFLAGS environment variable to your native architecture
  # On Windows:
  #   gem install mysql
  #       Choose the win32 build.
  #       Install MySQL and put its /bin directory on your path.
  #
  # And be sure to use new-style password hashing:
  #   http://dev.mysql.com/doc/refman/5.0/en/old-client.html
  development:
    adapter: mysql
    encoding: utf8
    database: flexigrid_development
    username: root
    password:
    host: localhost

  # Warning: The database defined as 'test' will be erased and
  # re-generated from your development database when you run 'rake'.
  # Do not set this db to the same as development or production.
  test:
    adapter: mysql
    encoding: utf8
    database: flexigrid_test
    username: root
    password:
    host: localhost

  production:
    adapter: mysql
    encoding: utf8
    database: flexigrid_production
    username: root
    password:
    host: localhost

Step 5: Create the MySQL database and import the sample data

If you use phpMyAdmin, follow the instructions below. If you use other database administration tools, please consult the proper methods to create a new MySQL database and import data from .sql files.

Step 6: Create the Views

From your Rails application directory, go to app/views/layouts, create a new file and paste the following into the file. Save the file as application.rhtml.


<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
  <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
    <link href="/javascripts/css/flexigrid/flexigrid.css" media="screen" rel="stylesheet" type="text/css" />
    <script src="/javascripts/jquery-1.2.3.js" type="text/javascript"></script>
    <script src="/javascripts/flexigrid.js" type="text/javascript"></script>
    <title>Flexigrid on Rails - by Nick Fessel
    <style>
      body
      {
        background: #fff;
        margin-left: 25%;
        margin-top: 10%;
        padding: 20px;
        font-family: Arial, Helvetica, sans-serif;
        font-size: 12px;
        color: #333;
      }

      h1
      {
        font-size: 26px;
	font-weight: normal;
	margin: 0px;
	color: #0099FF;
      }

      #byline
      {
      font-size:14px
      }
    </style>
  </head>
  <body>
    <%= yield %>
  </body>
</html>

From your Rails application directory, go to app/views/countries, create a new file and paste the following into the file. Save the file as list.rhtml.


<h1><strong>Flexigrid</strong> on Rails<span id="byline"> by <a
href="http://www.nickfessel.com">Nick Fessel</a></span></h1>
<table id="flex1"></table>
<script type="text/javascript">
  $("#flex1").flexigrid
    (
    {
    url: 'http://localhost:3000/countries/grid_data',
    dataType: 'json',
    colModel : [
      {display: 'ISO', name : 'iso', width : 40, sortable : true, align: 'left'},
      {display: 'Name', name : 'name', width : 180, sortable : true, align: 'left'},
      {display: 'Printable Name', name : 'printable_name', width : 120, sortable : true, align: 'left'},
      {display: 'ISO3', name : 'iso3', width : 130, sortable : true, align: 'left', hide: true},
      {display: 'Numcode', name : 'numcode', width : 120, sortable : true, align: 'left'},
    ],
    searchitems : [
      {display: 'Name', name : 'name'},
      {display: 'ISO', name : 'iso'}
    ],
    sortname: "iso",
    sortorder: "desc",
    usepager: true,
    title: 'Countries',
    useRp: true,
    rp: 15,
    showTableToggleBtn: true,
    width: 700,
    height: 200
    }
  );
</script>

Step 7: Set up the Countries Controller

Paste the following into app/Controllers/countries_controller.rb


class CountriesController < ApplicationController

  def list
  end

  def grid_data
    page = (params[:page]).to_i
    rp = (params[:rp]).to_i
    query = params[:query]
    qtype = params[:qtype]
    sortname = params[:sortname]
    sortorder = params[:sortorder]

    if (!sortname)
      sortname = "iso"
    end

    if (!sortorder)
      sortorder = "desc"
    end

    if (!page)
      page = 1
    end

    if (!rp)
      rp = 10
    end

    start = ((page-1) * rp).to_i
    query = "%"+query+"%"

    # No search terms provided
    if(query == "%%")
      @countries = Country.find(:all,
  	:order => sortname+' '+sortorder,
  	:limit =>rp,
  	:offset =>start
  	)
      count = Country.count(:all)
    end

    # User provided search terms
    if(query != "%%")
        @countries = Country.find(:all,
	  :order => sortname+' '+sortorder,
	  :limit =>rp,
  	  :offset =>start,
  	  :conditions=>[qtype +" like ?", query])
	count = Country.count(:all,
	  :conditions=>[qtype +" like ?", query])
    end

    # Construct a hash from the ActiveRecord result
    return_data = Hash.new()
    return_data[:page] = page
    return_data[:total] = count

    return_data[:rows] = @countries.collect{|u| {
  			   :cell=>[u.iso,
  			   u.name,
  			   u.printable_name,
  			   u.iso3,
    			   u.numcode]}}

    # Convert the hash to a json object
    render :text=>return_data.to_json, :layout=>false
  end
end

Step 8: Set up the Flexigrid and jQuery installations

Step 9: Run it!

Start your servers and browse to http://localhost:3000/countries/list

If all is well, you should see something like the following:

Try clicking the column headers to sort by column. Click the magnifying glass to search.

Congratulations! You just put Flexigrid on Rails!

Tips

Having difficulties? Follow every step carefully. This tutorial assumes that the developer knows how to create Ruby on Rails applications and manage MySQL databases.

If you still need help, post a comment. You can also e-mail me at nfessel (at) gmail (dot) com.

Thank you, Paulo

Special thanks go to Paulo P. Mariñas, the creator of Flexigrid. For more information about Flexigrid, please see webplicity.net/flexigrid.

comments Comments
Post a comment Post a comment

securitycode