Ajax on Rails

Bringing together Ajax and Rails with Prototype

Secure remote control for conventional and virtual desktops

In an earlier tutorial we discussed Ruby on Rails. Ajax is an XMLHttpRequest-based web technique that you can use to transfer data between a client application and a web server, and which lets you update sections of the web page without reloading it.

Rails supports Ajax functions where a XMLHttpRequest request may be sent to a web server and the XMLHttpRequest response updates the web page. In this article, we’ll develop a Rails Ajax web application which runs against MySQL database.

Rails provides support for Ajax in the Prototype JavaScript Framework, which is a set of methods that return the required JavaScript to implement the method. Some of the methods in the Prototype JavaScript framework are described in Table 1.

Table 1. Rails Prototype JavaScript Methods

Prototype Method Description
form_remote_tag Returns a form tag that will submit a form using XMLHttpRequest.
link_to_remote Returns a link to a remote object that is invoked using XMLHttpRequest
observe_field Observes a form and invokes a specified url using XMLHttptRequest. Updates innerHTML of an element of the specified DOM ID with XMLHttpRequest response text.
observe_form Similar to observe_field, but for a form.
periodically_call_remote Periodically invokes a specified url using XMLHttpRequest and updates a specified div with XMLHttpRequest response text.
submit_to_remote Returns a button input that will submit a form with XMLHttpRequest.
update_element_function Returns a JavaScript function that will update a specified element using XMLHttpRequest.
update_page Updates a web page using XMLHttpRequest.

We will create a rails application, railsapp, and then create a MySQL database table, catalogs, as explained in the Ruby on Rails tutorial. The database.yml configuration file and the migration script, 001_create_catalogs.rb are available in the Resources zip file.

Sending a Request

First, create a controller class and the view template with the following command:

C:/ruby/railsapp>ruby script/generate controller catalog index

A catalog_controller.rb Ruby file is generated in the railsapp/app/controllers directory. A view template, index.rhtml, is created in the railsapp/app/views/catalog directory. HTTP requests are initiated from the view template and processed by the Action Controller framework.

The Ajax functionality is implemented in the Prototype JavaScript framework, so you should include the prototype library with the following declaration in the <head> </head> section of the index.rhtml file:

<%= javascript_include_tag “prototype” %>

A XMLHttpRequest may be initiated using one of the methods described in Table 1. We’ll use the observe_field method. In index.rhtml, a text field is used to specify that a catalog section is polled at a specified frequency and a XMLHttpRequest request is sent to the web server. An article_list div in the web page is then updated with the XMLHttpRequest response text, which consists of an article list retrieved from the database.

Add a text field with text_field_tag method:

<%=text_field_tag:section %>

Specify the text field to observe and the div to update with the observe_field method:

<%= observe_field(:section, :frequency=>
0.1, :update=>
"article_list", :url=>
: get_article_list })%>

The observe_field method specifies that the :section text field is to be observed, with a polling frequency of :frequency seconds. The :update option specifies the div to be updated with XMLHttpRequest response text and :url specifies the controller action that is invoked at the polling frequency.

The index.rhtml view template is available in the Resources zip file.

Processing a Request

In the example application, the observe_field method sends a XMLHttpRequest request to the get_article_list action in the controller. The controller class obtains a data result set using an SQL query created from the section value specified in the view and then outputs a list of retrieved articles. The controller class, CatalogController, runs the SQL query using the model class, Catalog.

Create the model class, Catalog, with the following command:

C:/ruby/railsapp>ruby script/generate model  catalog

By default, a connection is established using the connection parameters in the database.yml file. By default, the table name used is the plural of the model class with the first letter lowercased. The database, table name, or other connection parameters may be set in the catalog.rb file using the establish_connection and set_tabe_name methods.

Modify the catalog.rb Ruby file to create a MySQL database connection. In the Catalog class, set the table name from which data is to be retrieved with the set_table_name method of the ActiveRecord::Base class thusly:

class Catalog < ActiveRecord::Base
set_table_name "catalogs" 

Next, establish a connection with the database with the establish_connection method. For a connection with the MySQL database, specify the :adapter value as “mysql” in lowercase:

   :adapter  => "mysql",
   :host     =>  "localhost",
   :database =>  “test”, 
   :username =>  "root",
   :password =>   

The complete listing for the catalog.rb model class is available in the Resources zip file.

The controller class CatalogController (catalog_controller.rb file) integrates the model with the view. CatalogController consists of actions index and get_article_list. The index action has a corresponding view template in the views/catalog directory.

In the get_article_list method, we retrieve the value of the section text field:


Then we construct a local variable, @catalogList, for a list of articles retrieved for a section:


The ActiveRecord::Base class provides various finder methods to query a database.

We run a SQL query with a SELECT statement using the specified section value and then iterate over the result set to construct a list of articles that match the section value:

Catalog.find_by_sql("SELECT * from catalogs WHERE SECTION='"+@section+"'").each do|catalog|
@catalogList+="<li><a href=\""+catalog.url+"\">" +catalog.title+ "</a></li>"

We return the response to the index.rhtml view with render:text:

render:text=> @catalogList

The controller script, catalog_controller.rb, is available in the Resources zip file.

Processing a Response

The response from the controller class is used to update the article_list div specified in the :update option of the observe_field method. We’ll now run the MVC Ruby on Rails application after first starting the WEBrick web server:

C:/ruby/railsapp>ruby script/server

The web server can be accessed using url http://localhost:3000/ and we can invoke the index action of the Catalog controller with url http://localhost:3000/Catalog/index in a web browser. This displays an input form (Figure 1 Search Form):

Figure 1. Search Form.

We specify a section field value and if the specified section value does not match a section value in the database, an article list is not displayed (Figure 2. Specifying a Section Value.):

Figure 2. Specifying a Section Value.

We chose to specify a section value that matches a section in the database table catalogs, such as ‘XML’, for example. A list of articles that match the specified section is displayed without clicking on a button (Figure 3. Catalog Search Result.):

Figure 3. Catalog Search Result.

A Rails-implemented Ajax application is simpler to develop than an ordinary J2EE Ajax application, so many enterprise organisations are using Ruby on Rails (see “Who is already on Rails?” at the homepage here).

Top 5 reasons to deploy VMware with Tegile

More from The Register

next story
New 'Cosmos' browser surfs the net by TXT alone
No data plan? No WiFi? No worries ... except sluggish download speed
iOS 8 release: WebGL now runs everywhere. Hurrah for 3D graphics!
HTML 5's pretty neat ... when your browser supports it
Mathematica hits the Web
Wolfram embraces the cloud, promies private cloud cut of its number-cruncher
Mozilla shutters Labs, tells nobody it's been dead for five months
Staffer's blog reveals all as projects languish on GitHub
'People have forgotten just how late the first iPhone arrived ...'
Plus: 'Google's IDEALISM is an injudicious justification for inappropriate biz practices'
SUSE Linux owner Attachmate gobbled by Micro Focus for $2.3bn
Merger will lead to mainframe and COBOL powerhouse
iOS 8 Healthkit gets a bug SO Apple KILLS it. That's real healthcare!
Not fit for purpose on day of launch, says Cupertino
prev story


Secure remote control for conventional and virtual desktops
Balancing user privacy and privileged access, in accordance with compliance frameworks and legislation. Evaluating any potential remote control choice.
Intelligent flash storage arrays
Tegile Intelligent Storage Arrays with IntelliFlash helps IT boost storage utilization and effciency while delivering unmatched storage savings and performance.
WIN a very cool portable ZX Spectrum
Win a one-off portable Spectrum built by legendary hardware hacker Ben Heck
High Performance for All
While HPC is not new, it has traditionally been seen as a specialist area – is it now geared up to meet more mainstream requirements?
Beginner's guide to SSL certificates
De-mystify the technology involved and give you the information you need to make the best decision when considering your online security options.