devxlogo

Combine jqGrid and Rails for Beautified Business Applications

Combine jqGrid and Rails for Beautified Business Applications

JqGrid is a feature-rich data grid built with the jQuery JavaScript library. Short for “jQuery grid,” JqGrid has been around for quite a while and comes with rather extensive documentation. Hence, this article will not get into the details of installing jqGrid or using jQuery for rendering. It simply provides the basic steps for creating a simple application in Rails with jqGrid.

Using jqGrid in a Rails View

First and foremost, you have to integrate jqGrid with a Rails application. It is assumed that you have already installed the jqGrid plug-in for Rails. Once the plug-in has been installed properly, you would see the folder (your_app)/vendor/plugins/2dc_jqgrid.

Once you have installed jqGrid, jqGrid has to be imported to your Rails application. This is done by including the following tags:

           

in your app view file (e.g., index.html.erb).

Once jqGrid has been imported, you have to create a jqGrid. A good place to include a jqGrid will be in the jQuery(document).ready(function() as shown below. Note, this is a JavaScript code and has to be within the tags.

         var mygrid = jQuery("#item_instance").jqGrid({               url:'/item_instances?q='+ ,               editurl:'/item_instances/update?q='+,               datatype: "json",               colNames:['ID','NAME','DISPLAY NAME'],               colModel:[{name:'id', index:'id',resizable:false,width:35},
{name:'NAME', index:'NAME',edittype:'text',editable:true},
{name:'DISPLAY_NAME', index:'DISPLAY_NAME',edittype:'text',editable:true}], pager: '#item_instance_pager', rowNum:10, rowList:[10,25,50,100], imgpath: '/images/jqgrid', sortname: '', viewrecords: true, height:300, width: 500, sortorder: '', gridview: false, scrollrows: true, autoheight: false, autowidth: false, rownumbers: false, multiselect: false, subGrid: false, caption: "Item Instances" }).navGrid('#item_instance_pager', {edit:false,add:true,del:true,search:true,refresh:true}, {afterSubmit:function(r,data){return true;(r,data,'edit');}}, {afterSubmit:function(r,data){return true;(r,data,'add');}}, {afterSubmit:function(r,data){return true;(r,data,'delete');}} ) mygrid.filterToolbar();mygrid[0].toggleToolbar() });

Next, you have to declare an HTML table that actually gets rendered.

              target="_blank">

One can easily understand that item_instance is the actual HTML table that gets beautified using jQuery and some CSS to make it really look professional.

In the table that gets created (item_instance), you can see a “url” and an “edit_url.” Url typically maps to the index method of the controller class, and edit_url, as the value suggests, is mapping to the update method of the ItemInstances controller class. The datatype field suggests that the medium of communication between the controller and the view is json.

The colNames field tells us the fields that are going to be displayed and their captions. In our case, a display of our table will look as shown in the image below:

The colNames are “ID”, “NAME” and “DISPLAY NAME,” respectively. The colMode tells you the type of the data that is displayed. It’s a common practice to make the field ID non-editable. However, the fields NAME and DISPLAY NAME are editable.

The rowList parameter is the one that can be seen as a drop-down box, near the arrow at the bottom of the image. The options are 10, 25, 50 and 100. This lets you view a max of 10 or 25 or 50 or 100 entries at a time, whichever you chooses. The rowNum is the value that the we tell the system choose by default.

Finally, there is a navigation grid that lets you carry out the CRUD operations. Users have to define the portion shown below in order to get the respective icons for add, edit and delete.

navGrid('#item_instance_pager',               {edit:false,add:true,del:true,search:true,refresh:true},               {afterSubmit:function(r,data){return true;(r,data,'edit');}},               {afterSubmit:function(r,data){return true;(r,data,'add');}},               {afterSubmit:function(r,data){return true;(r,data,'delete');}}             )

That’s it, and the view part is done. Now you have to get the server-side code in place.

Using jqGrid with a Rails Controller

At the server side, for a simple table, all that you have to do is to get the data from the table and send that in JSON format to the view.

        @item_instances = ItemInstance.find(:all, :conditions => ["ITEM_METADATA_ID = ?", params[:q]],                   :limit => params[:rows],                   :offset => (params[:page].to_i - 1) * params[:rows].to_i);         respond_to do |format|             format.html             format.json { render :json => @item_instances.to_jqgrid_json([:id, :NAME,:DISPLAY_NAME],                                                        params[:page], params[:rows], params[:records]) }         end 

Note that the Rails jqGrid plug-in has a to_jqgrid_json function, which converts the ItemInstance object to JSON format, which the jqGrid in the view can display. Although this will make sure that data is fetched from the server side and displayed as shown in Figure 1, the CRUD operations won’t be complete.

  def post_data           if params[:oper] == "del"             ItemInstance.find(params[:id]).destroy           else             @item_instance = { :id => params[:id], :ITEM_METADATA_ID => params[:q], 
:NAME => params[:NAME], :DISPLAY_NAME => params[:DISPLAY_NAME] } if params[:id] == "_empty" ItemInstance.create(@item_instance) else ItemInstance.find(params[:q]).update_attributes(@item_instance) end end render :nothing => true end

In the previous sections, the usage of jqGrid along with Ruby on Rails was discussed in detail. In the following section, the focus will predominantly be on making the CRUD operations look a bit more professional and how you can achieve this with the help of jqGrid and a bit of supporting jQuery scripts.

CRUD Icons in jqGrid

JqGrid provides the users with a set of icons for the CRUD operations as shown in Figure 2 below:


Figure 2. JqGrid Icons for CRUD Operations

The icons are provided by jqGrid out of the box, and they can be enabled or disabled to suit the user’s needs. In the snippet below, you can see that there are a set of true and false conditions. “Edit:false” when declared in the navGrid disables the edit icon (the edit icon disables from the table). It also disables editing of the rows of the table. “Edit:true,” on the other hand, would have enabled the edit icon and let the users edit the contents. Though the edit icons on the table (ui) can be enabled and disabled, it does not actually mean that the functionality of editing and save, or deleting and save has been enabled at the back end. This has to be explicitly enabled by the user. From the code below, one can notice easily that “edit” has been disabled. However, add, delete, search and refresh are enabled. The users can only see the icons of the operations that have been enabled (Figure 2).

navGrid('#item_instance_pager',{edit:false,add:true,del:true,search:true,refresh:true},{afterSubmit:function(r,data){return true;(r,data,'edit');}},{afterSubmit:function(r,data){return true;(r,data,'add');}},{afterSubmit:function(r,data){return true;(r,data,'delete');}})

CRUD Params from jqGrid to Rails Controller

The params to the controllers in any Rails app are typically held in the params map. However, unlike the controller/method convention that Rails uses, the parameters related to CRUD operations from jqGrid are specific values and passed through the params map.

def post_dataif params[:oper] == "del"ItemInstance.find(params[:id]).destroyelse@item_instance = { :id => params[:id], :ITEM_METADATA_ID => params[:q], :NAME => params[:NAME],:DISPLAY_NAME => params[:DISPLAY_NAME]}if params[:id] == "_empty"ItemInstance.create(@item_instance)elseItemInstance.find(params[:q]).update_attributes(@item_instance)endendrender :nothing => trueend

The creation (addition) of a new row in the table is indicated by the “params[:id] == "_empty"” parameter. In case the row is already present and you have edited the row, then the “params[:id]” will contain an integer value. The deletion (removal) of a row is indicated by the “params[:oper] == "del"” field. In the case of delete operation, the “params[:id] ” field will also contain the id of the row that you have selected for deletion. The method post_data within the controller actually acts as an interface to actual operations, and it overrides the Rails’ conventional method of controller/create for creation, controller/destroy for deletion, etc. However, it is still a good idea to use post_data as a wrapper to the actual method in the convention hierarchy. This ensures that the convention is not broken. This is done by passing the data to the respective method as shown below:

def post_dataif params[:oper] == "del"destroyelseif params[:id] == "_empty"createelseItemInstance.find(params[:q]).update_attributes(@item_instance)endendrender :nothing => trueend

Users may choose to delete multiple rows at the same time. In the case of multiple selections, the selected elements’ ids are separated by a comma as shown below:

Def destroyids = params[:id].split(",");@instances = ItemInstance.find(ids)if(@instances.nil?)puts "**********************"puts "No item found for deletion"puts "**********************"[email protected] do |instance|instance.destroyend@instances = ItemInstance.find(:all, :limit => params[:rows],:offset => (params[:page].to_i - 1) * params[:rows].to_i);end

A read typically is handled using the find method of the Model. In this particular case, ItemInstance is the model and ItemInstancesController is the controller. One can also notice that the number of records that are fetched is controlled through the params[:rows] and params[:page] parameters. As shown in Figure 2, jqGrid also comes with a drop-down selector which can be used to control the number of rows that one would want to see in the table at a time. The values selected form the UI will determine the values of params[:rows] and params[:page] respectively.

This makes the story complete. With the definition of the method post_data, the integration of the CRUD that was talked about earlier becomes complete. The ‘del’ and ‘add’ which had been declared in navGrid of the view has now been connected to the post_data method of the ItemInstancesController. As a good practice, it is better to let the Rails methods create, update and destroy to the necessary CRUD operations and not let post_data do the same.

References and Acknowledgements

  1. I suggest the reader go through www.trirand.com for the great grid plug-in called jqGrid.
  2. I would also suggest the readers go through www.2dconcept.com for a great Rails plugin that makes our life much easier, while integrating Rails with jqGrid.
  3. It would be great to look into www.rubyonrails.org for any help related to installing Ruby on Rails, especially if you is a beginner.
  4. Exploring www.jquery.com and www.plugins.jquery.com will also be worthwhile.
devxblackblue

About Our Editorial Process

At DevX, we’re dedicated to tech entrepreneurship. Our team closely follows industry shifts, new products, AI breakthroughs, technology trends, and funding announcements. Articles undergo thorough editing to ensure accuracy and clarity, reflecting DevX’s style and supporting entrepreneurs in the tech sphere.

See our full editorial policy.

About Our Journalist