Ajax on Rails

Bringing together Ajax and Rails with Prototype

The essential guide to IT transformation

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).

Secure remote control for conventional and virtual desktops

More from The Register

next story
BBC: We're going to slip CODING into kids' TV
Pureed-carrot-in-ice cream C++ surprise
China: You, Microsoft. Office-Windows 'compatibility'. You have 20 days to explain
Told to cough up more details as antitrust probe goes deeper
Linux turns 23 and Linus Torvalds celebrates as only he can
No, not with swearing, but by controlling the release cycle
Scratched PC-dispatch patch patched, hatched in batch rematch
Windows security update fixed after triggering blue screens (and screams) of death
This is how I set about making a fortune with my own startup
Would you leave your well-paid job to chase your dream?
prev story


Endpoint data privacy in the cloud is easier than you think
Innovations in encryption and storage resolve issues of data privacy and key requirements for companies to look for in a solution.
Implementing global e-invoicing with guaranteed legal certainty
Explaining the role local tax compliance plays in successful supply chain management and e-business and how leading global brands are addressing this.
Advanced data protection for your virtualized environments
Find a natural fit for optimizing protection for the often resource-constrained data protection process found in virtual environments.
Boost IT visibility and business value
How building a great service catalog relieves pressure points and demonstrates the value of IT service management.
Next gen security for virtualised datacentres
Legacy security solutions are inefficient due to the architectural differences between physical and virtual environments.