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.
- Create a new database called flexigrid_development.
- Click the Import Tab and select your iso_country_list.sql file.
- Click Go.
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
- Extract flexigrid.zip to public/javascripts
- Put jquery1-2-3.js into public/javascripts
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
Post a comment


Thanks for posting this code
Been researching so many widget/grid solutions that I am cross-eyed now, but of all the ones I have tried this one seems to suit my requirements best. (Gotta love that its jQuery as well)
All I need now is a calendar date-picker and a rich text editor (besides TinyMCE) Any suggestions?
Yes Flexigrid is a great datagrid. It also has edit/delete/add functionality which I did not cover in this post. Definitely check it out.
For date selection in my Rails projects, I use calendar_date_select . It is easy to use, free and it works great.
I haven't used rich text editors much, but I will let you know if I find a decent one.
-Nick
thanks for you help.
From my brief inspection of the source, Flexigrid uses jQuery's low-level AJAX implementation to load data from a url. Passing a JSON object would require changes to the underlying code for Flexigrid.
I suggest browsing to the url in question and making sure that the url returns the JSON representation of your data. If the url does not return JSON, then Flexigrid will never load the data anyway. Start small- get the JSON working at the url and then add Flexigrid.
Feel free to provide more details about what is not working and I will see how I can help.
If you open a browser and navigate to the url, does it display the JSON?
Also, incorrect structure of the JSON may result in failed loading of the Flexigrid. Make sure the JSON structure is correct.
-Nick
Van
I have not seen display:none in the rows. However, initially my JSON object had incorrect formatting and it caused incorrect loading of the grid rows- in fact, the rows did not display at all. Perhaps the JSON format is incorrect in yours?
Flexigrid functions with the examples, so I suspect the problem is not flexigrid.js but something in your code.
Nick
I used your example to demonstrate Flexigrid on Google App Engine. Everything was pretty analogous, right down to the code used to generate the JSON response.
http://flexi-gae.appspot.com/
I can't see anything in http://localhost:3000/countries/list
the page is yust white
I do every step many times
please comment one possible problem
I need this
in the application.rhtml if you yust copy the text this miss the
That Google App Engine example is great! I am glad I could help by providing the original Rails code. Thanks.
Nick
"ok , I find the little stupid problem
in the application.rhtml if you yust copy the text this miss the" + >/title<
Good question. I am sure that adding hyperlinks to each row is possible.
Since the Flexigrid JavaScript code builds the rows from the passed JSON object, the Flexigrid JavaScript must be modified to build hyperlinks. This means that the JSON object must have an identifier to indicate a hyperlink- the identifier could be the position of the element in the JSON object. I will look into it and post an update comment on this entry. Thanks.
Nick
Thank you very much for your quick reply. I am also looking into it while waiting for your post. I really appreciate your help.
Canvas
$("#flex1').append('tr id= "newRow">
to add the row. Then I figured I could search for all rows with an id of "newRow" and save them to the database when the user presses Save. But how can I actually add/edit the data in a new row?
Please check the CodeIgniter forum at http://codeigniter.com/forums/viewthread/75326/ for answers to configuring Flexigrid. This forum contains information from the creator of Flexigrid. There is information in the forum regarding adding, editing, updating and deleting rows.
Nick
I've been in "evaluation mode" of Ruby on Rails for a little while trying to determine if this is the right framework for replacing our central internal management application. One of the items I have been looking for is an easy to implement, sortable grid and this is it. I really appreciate your example as it has helped me to see that this goal is possible. Just two questions, as I said, I'm in eval mode on Ruby so I'm still a noob to Ruby programming. How difficult would it be to incorporate filtering within this grid (or externally)? Could you provide a simple pseudo example?
Thanks,
Henry