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.
devx-admin

devx-admin

Share the Post:
Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023,

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed

Poland Energy Future

Westinghouse Builds Polish Power Plant

Westinghouse Electric Company and Bechtel have come together to establish a formal partnership in order to design and construct Poland’s inaugural nuclear power plant at the Lubiatowo-Kopalino site in Pomerania.

EV Labor Market

EV Industry Hurting For Skilled Labor

The United Auto Workers strike has highlighted the anticipated change towards a future dominated by electric vehicles (EVs), a shift which numerous people think will result in job losses. However,

Soaring EV Quotas

Soaring EV Quotas Spark Battle Against Time

Automakers are still expected to meet stringent electric vehicle (EV) sales quotas, despite the delayed ban on new petrol and diesel cars. Starting January 2023, more than one-fifth of automobiles

Affordable Electric Revolution

Tesla Rivals Make Bold Moves

Tesla, a name synonymous with EVs, has consistently been at the forefront of the automotive industry’s electric revolution. The products that Elon Musk has developed are at the forefront because

Sunsets' Technique

Inside the Climate Battle: Make Sunsets’ Technique

On February 12, 2023, Luke Iseman and Andrew Song from the solar geoengineering firm Make Sunsets showcased their technique for injecting sulfur dioxide (SO₂) into the stratosphere as a means

AI Adherence Prediction

AI Algorithm Predicts Treatment Adherence

Swoop, a prominent consumer health data company, has unveiled a cutting-edge algorithm capable of predicting adherence to treatment in people with Multiple Sclerosis (MS) and other health conditions. Utilizing artificial

Personalized UX

Here’s Why You Need to Use JavaScript and Cookies

In today’s increasingly digital world, websites often rely on JavaScript and cookies to provide users with a more seamless and personalized browsing experience. These key components allow websites to display

Geoengineering Methods

Scientists Dimming the Sun: It’s a Good Thing

Scientists at the University of Bern have been exploring geoengineering methods that could potentially slow down the melting of the West Antarctic ice sheet by reducing sunlight exposure. Among these

why startups succeed

The Top Reasons Why Startups Succeed

Everyone hears the stories. Apple was started in a garage. Musk slept in a rented office space while he was creating PayPal with his brother. Facebook was coded by a

Bold Evolution

Intel’s Bold Comeback

Intel, a leading figure in the semiconductor industry, has underperformed in the stock market over the past five years, with shares dropping by 4% as opposed to the 176% return

Semiconductor market

Semiconductor Slump: Rebound on the Horizon

In recent years, the semiconductor sector has faced a slump due to decreasing PC and smartphone sales, especially in 2022 and 2023. Nonetheless, as 2024 approaches, the industry seems to

Elevated Content Deals

Elevate Your Content Creation with Amazing Deals

The latest Tech Deals cater to creators of different levels and budgets, featuring a variety of computer accessories and tools designed specifically for content creation. Enhance your technological setup with

Learn Web Security

An Easy Way to Learn Web Security

The Web Security Academy has recently introduced new educational courses designed to offer a comprehensible and straightforward journey through the intricate realm of web security. These carefully designed learning courses

Military Drones Revolution

Military Drones: New Mobile Command Centers

The Air Force Special Operations Command (AFSOC) is currently working on a pioneering project that aims to transform MQ-9 Reaper drones into mobile command centers to better manage smaller unmanned

Tech Partnership

US and Vietnam: The Next Tech Leaders?

The US and Vietnam have entered into a series of multi-billion-dollar business deals, marking a significant leap forward in their cooperation in vital sectors like artificial intelligence (AI), semiconductors, and

Huge Savings

Score Massive Savings on Portable Gaming

This week in tech bargains, a well-known firm has considerably reduced the price of its portable gaming device, cutting costs by as much as 20 percent, which matches the lowest

Cloudfare Protection

Unbreakable: Cloudflare One Data Protection Suite

Recently, Cloudflare introduced its One Data Protection Suite, an extensive collection of sophisticated security tools designed to protect data in various environments, including web, private, and SaaS applications. The suite

Drone Revolution

Cool Drone Tech Unveiled at London Event

At the DSEI defense event in London, Israeli defense firms exhibited cutting-edge drone technology featuring vertical-takeoff-and-landing (VTOL) abilities while launching two innovative systems that have already been acquired by clients.

2D Semiconductor Revolution

Disrupting Electronics with 2D Semiconductors

The rapid development in electronic devices has created an increasing demand for advanced semiconductors. While silicon has traditionally been the go-to material for such applications, it suffers from certain limitations.

Cisco Growth

Cisco Cuts Jobs To Optimize Growth

Tech giant Cisco Systems Inc. recently unveiled plans to reduce its workforce in two Californian cities, with the goal of optimizing the company’s cost structure. The company has decided to

FAA Authorization

FAA Approves Drone Deliveries

In a significant development for the US drone industry, drone delivery company Zipline has gained Federal Aviation Administration (FAA) authorization, permitting them to operate drones beyond the visual line of

Mortgage Rate Challenges

Prop-Tech Firms Face Mortgage Rate Challenges

The surge in mortgage rates and a subsequent decrease in home buying have presented challenges for prop-tech firms like Divvy Homes, a rent-to-own start-up company. With a previous valuation of

Lighthouse Updates

Microsoft 365 Lighthouse: Powerful Updates

Microsoft has introduced a new update to Microsoft 365 Lighthouse, which includes support for alerts and notifications. This update is designed to give Managed Service Providers (MSPs) increased control and

Website Lock

Mysterious Website Blockage Sparks Concern

Recently, visitors of a well-known resource website encountered a message blocking their access, resulting in disappointment and frustration among its users. While the reason for this limitation remains uncertain, specialists