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
As you know, I already e-mailed you regarding customizing Flexigrid. Just let me know if you need any further assistance. Thank you,
Nick
Thanks for the rails adaptation nick.
Due to strong interest, I am working on a new post titled Customizing Flexigrid and I will be sure to cover the topics you mention. Thank you,
Nick
I found FlexiGrid is really flexible. Now there is some thing that i need for my app, i only just have a html page and the data in java script array or JSON format. So how do i use flexi grid for all features on the client side. I would be grateful if u mail the solution.
Thanks in advance,
Mahidhar Ch.
Flexigrid's design involves querying a data source. Your application then needs to send the results of the query back to Flexigrid.
How do you propose to query a file containing static JSON data and then send only the results back to Flexigrid?
Nick
If you are running the latest version of Flexigrid, version 1.03b, you may find that my Rails example does not function.
To fix the problem, please do the following:
Change this:
return_data[:rows] = @countries.collect{|u| {
:cell=>[u.iso,
u.name,
u.printable_name,
u.iso3,
u.numcode]}}
To this:
return_data[:rows] = @countries.collect{|u| {:id=>u.iso,
:cell=>[u.iso,
u.name,
u.printable_name,
u.iso3,
u.numcode]}}
There was a slight change to the JSON format required for Flexigrid.
I am currently running Flexigrid 1.03b on Rails 2.1.1 with no problems.
Thanks,
Nick
No problem at all. I had fun putting it together.
-Nick
I have recently started using the flexigrid with some of my web applications. However, I am running into some problems in IE6 with sorting.
Try going to this page: http://sanderkorvemaker.nl/test/flexigrid/ and sort back and forth on different columns and eventually the browser will encounter an error.
I have not been able to reproduce the problem in Firefox or IE7. So it seems to be a problem with IE6 but has anyone else encountered it? Any ideas on how to fix?
Thanks
Rich
I'd like to know if there's any way to pre-select items displayed in Flexigrid.
Say on the first load of the above example I#d like to have Zimbabwe preselected.
Any help is much appreciated!
Joseph
One way to accomplish that would be to create a javascript function that executes after the body has loaded. Say...
Then inside the load() function you could get the rows by their id's. Each row has an id of "row" + the id that's passed in through the data file (either XML or JSON data). For Zimbabwe the row id would be id="rowZW". So your load function would look like this:
function load()
{
var r = document.getElementById("rowZW");
if(r) r.className = "trSelected";
}
Of course this only works on the initial load of the page. If you sort off of Zimbabwe and then come back it won't be selected anymore.
Maybe not the best solution but it's a start.
Rich
Looks great super, I not able to set/place/align this grid at the top left corner of my page.Please help me to solve,
Thanks in advance,
Saravanan.K
When i include,<%= javascript_include_tag :defaults %> in application.rhtml file the grid was not loaded. could any one suggest on this isseu.
I have tried to include all javascript file seperately like,
<%= javascript_include_tag :effects %><%= javascript_include_tag :controls %>
but all requires prototype.js file to be included,
so when i include prototype.js file the grid was not loaded.
Without including prototype.js file the grid works fine. could any one please suggest on this issue.
Thanks in advance
Regards,
Jose Martin
When i include,
"javascript_include_tag :defaults"
in application.rhtml file the grid was not loaded. could any one suggest on this issue.
I have tried to include all javascript file seperately like,
"javascript_include_tag :effects"
"javascript_include_tag :controls"
but all requires prototype.js file to be included,
so when i include prototype.js file the grid was not loaded.
Without including prototype.js file the grid works fine. could any one please suggest on this issue.
Thanks in advance
Regards,
Jose Martin
Does anyone know if there is an issue with IE 7.0?
protect_from_forgery :except => .. whatever you need
I'm really new to Ruby on Rails and hope this can be useful for somebody
I am glad the tutorial worked well for you, and thanks for the tip.
Nick
I am using flexigrid using query with inner join, this is my query;
SELECT log.id, ope.nombre as operario,log.accion, log.controlador,log.log, log.fecha, log.ip FROM `log` log
INNER JOIN operario ope ON log.id_operario = ope.id
But I can't search by "operario". Please help me.
Thanks
Thanks,
Will Emerson
In your searchitems:[] list what do you have as the name: attribute for operario? Name: needs to be the column name in the database to make the search work.
Rich
so acrescentando, para versões 2.x usar o trecho
protect_from_forgery :except => [:grid_data]
, no controller, para evitar a validação de token do rails...
att,
att,
I've just been trying the examaple, however I get the following error in Firebug when trying to render the table:-
row.cell is undefined
http://localhost:4567/flexigrid/flexigrid.js
Line 426
Any body have any ideas?
Regards,
Carl
thanks
I am trying as it is example of yours, but its not working in my case, what I can see is the table grid without any records.
I am running wid ruby-1.8.6 and rails-1.2.6, please help me.
I think JSON is causing some issues.
Thanks
Puneet
Also if you are returning an empty grid, make sure the URL in list.html.erb is correct. For example I changed http://localhost to http://127.0.0.1 to fix this problem. (Hint check your database.yml for a socket: or host: entry and match it in your request)
Thanks to Nick for this good example.
If I try a newer jquery, I just get a "connection error" at the bottom of the grid.
We're sorry, but something went wrong.
We've been notified about this issue and we'll take a look at it shortly.