Feeds

Ajax on Rails

Bringing together Ajax and Rails with Prototype

Boost IT visibility and business value

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=>
{:action=>
: 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" 
end

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:

ActiveRecord::Base.establish_connection(
   :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:

@section=request.raw_post

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

@catalogList="<ol>"

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>"
   end 

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

Build a business case: developing custom apps

More from The Register

next story
PEAK LANDFILL: Why tablet gloom is good news for Windows users
Sinofsky's hybrid strategy looks dafter than ever
Leaked Windows Phone 8.1 Update specs tease details of Nokia's next mobes
New screen sizes, dual SIMs, voice over LTE, and more
Fiendishly complex password app extension ships for iOS 8
Just slip it in, won't hurt a bit, 1Password makers urge devs
Mozilla keeps its Beard, hopes anti-gay marriage troubles are now over
Plenty on new CEO's todo list – starting with Firefox's slipping grasp
Apple: We'll unleash OS X Yosemite beta on the MASSES on 24 July
Starting today, regular fanbois will be guinea pigs, it tells Reg
Another day, another Firefox: Version 31 is upon us ALREADY
Web devs, Mozilla really wants you to like this one
Secure microkernel that uses maths to be 'bug free' goes open source
Hacker-repelling, drone-protecting code will soon be yours to tweak as you see fit
Cloudy CoreOS Linux distro declares itself production-ready
Lightweight, container-happy Linux gets first Stable release
prev story

Whitepapers

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.
Boost IT visibility and business value
How building a great service catalog relieves pressure points and demonstrates the value of IT service management.
Why and how to choose the right cloud vendor
The benefits of cloud-based storage in your processes. Eliminate onsite, disk-based backup and archiving in favor of cloud-based data protection.
The Essential Guide to IT Transformation
ServiceNow discusses three IT transformations that can help CIO's automate IT services to transform IT and the enterprise.
Maximize storage efficiency across the enterprise
The HP StoreOnce backup solution offers highly flexible, centrally managed, and highly efficient data protection for any enterprise.