Ruby on Rails Part 2

Here goes

Securing Web Applications Made Simple and Scalable

Tutorial In the previous introductory Ruby on Rails article, we created an Oracle database table. In this article we shall develop a Model-View-Controller (MVC) CRUD (Create, Read, Update, and Delete functionality) application using Ruby on Rails. Rails is a combination of the following sub-projects…

  1. Model: Active Record is an object relational mapping package built on the Active Record pattern.
  2. Control: Action Controller (Action Pack package)
  3. View: Action View (Action Pack package)

Active Record integrates business objects and database tables to create a persistable domain model. Active record does not require any configuration files. Active Record uses transactions for database operations. The ActiveRecord::Base class is used to create a connection with the database, create a database record, find a database record, update a record and delete a record. Some of the methods in the ActiveRecord::Base class are discussed in following table.

Method Description
establish_connection() Establishes a connection to the database.
set_table_name() Sets the table name.
set_primary_key() Sets the primary key.
create() Creates an object and saves it as a record.
find(*) The find() method may be used with one of the following retrieval methods: Find by id: Finds a record for a specified id or a list/array of ids. Find first: Retrieves the first record that matches the specified options. Find all: Retrieves all the records that match the specified options. Some of the options that may be specified are: :conditions: An SQL fragment such as “catalogId=catalog1”. :limit: An integer specifying a limit on the number of records returned. :offset:An integer specifying the row offset to retrieve rows. For example, if :offset is 5, the first 4 rows are skipped. :select: Specifies a SELECT statement to retrieve rows. By default SELECT * FROM is used.
find_by_sql(sql) Retrieves a result set for the specifies SELECT statement.
update() Updates a record.
update_all() Updates all records.
delete() Deletes a record.

Next, we shall discuss each of these methods with an example. An example of creating an Oracle database connection with the establish_connection method is as follows:

  :adapter  => "oci",
  :host     => "",
  :username => "oe",
  :password => "oracle" 
   :database => “ORCL”

The :adapter key specifies a database adapter in lower-case. Table name and primary key may be set in a model class that extends the ActiveRecord::Base class as in following listing:

class Catalog < ActiveRecord::Base
set_table_name "catalogs" 
set_primary_key "catalogid"

The create method is used to create a record. For example, to add a record with values specified for column1, column2 and column3:

Catalog.create :column1 => "column1value", :column2 => "column2value", :column3 => "column3value"

The find method is used to find a record. For example, to find the first record that matches the SQL section:

find(:first, :conditions => "section = 'SQL'")

The find_by_sql method finds a result set for a specified SQL statement. An example of find_by_sql, in which a result set is created for the SQL section, is as follows:

@resultset=Catalog.find_by_sql("SELECT * from catalogs WHERE SECTION='SQL'")

The update method updates a record for the specified id. For example, the following listing updates journal and title columns of a row with id 1:

Catalog.update (1, {:journal=>'Oracle Magazine', title=>'Introduction to Ruby on Rails'} ) 

The update_all method updates all the records. For example, update all records to set journal to “Oracle Magazine” and publisher to “Oracle Publishing” like this:

Catalog.update_all "journal='Oracle Magazine',  publisher='Oracle Publishing'"

The delete method deletes a record. For example, to delete a record with id 10:


An Action Controller is made up of one or more actions (methods) that perform business logic and then either render a template or redirect to another action or a page. An action is defined as a public method and assumes that you want to render a template matching the name of the action when the method code has run. You may also redirect to an action or a page with redirect_to as in the following listing which redirects to a controller action index:

redirect_to :action=>”index” 

Redirect_to:back redirects back to the page that issued the request. A request is sent to an Action Controller from a view template with the :action key. The :action key specifies name of an action in the Action Controller as shown in following listing:


The request parameters are sent to the controller action and the action code is run. The request parameters are available to a controller action with the params hash. For example, :section param may be retrieved in a controller action with params hash as shown below:


Each controller action results in a response that is constructed using renders and redirects. By default a controller action renders a view template with matching name. For example, an index action would render the index template. The local variables set in a controller action are available to the template rendered and a controller action may render a template other than the default template. For example, render a edit template as shown below:

render :template=>”edit” 

A controller action may render a template for another action. For example, a controller action may render template for another controller action index as shown in following listing:

render :action=>”index” 

A file may also be rendered from a controller action. For example, render a file template.rhtml as shown below:

render :file=>”template.rhtml” 

Text may be rendered in the view template that invokes a controller action with render:text as shown below:

render:text =>”Example of render text” 

A MVC Rails application consists of the following Ruby, RHTML and configuration files:

  1. View templates(.rhtml files) in the app/views directory.
  2. Model class in the app/models directory.
  3. Controller class in the app/controllers directory
  4. Database Configuration file (database.yml) in the config directory.

A MVC Ruby on Rails application may be developed either by creating the model and controller classes separately and adding scaffolding to the model class, or by creating the model and controller classes with the Scaffold generator. Scaffolding consists of controller actions, including controller logic, and corresponding view templates, which perform CRUD operations on the database using the Active Record class. If the scaffold generator is used to create the model and controller classes, the scaffolding also gets added. We shall discuss both the methods, and subsequently create example model and controller classes with the scaffold generator.

Creating Model and Controller Separately

A model class, catalog, is created with the following ruby command.

>ruby script/generate model catalog

This generates a ruby script catalog.rb in the models directory of the Rails application directory. The model class extends the ActiveRecord::Base class, which was discussed earlier. Ruby script generated with example ruby command is listed in following listing.

class Catalog < ActiveRecord::Base

The ‘<’ denotes that Catalog is a subclass of ActiveRecord::Base class. Scaffolding may be added to the model class with the scaffold method by adding scaffold:catalog thus:

class Catalog < ActiveRecord::Base

A controller class may be created with the following ruby command:

>ruby script/generate controller catalog

A controller class, CatalogController, which extends the ApplicationController class gets generated. ApplicationController is a subclass of the ActionController::Base class. The Controller ruby script, is shown in following listing:

class CatalogController < ApplicationController

By default, the following actions and views get generated by the scaffold method: index, list, show, new, create, edit, update, and destroy. If the default actions views are to be overridden, create view templates corresponding to the required actions. For example, to override the default view for edit action, create a view template edit.rhtml in the views directory of the Rails application.

Creating Model, Views, Controller with Scaffold Generator

The Rails framework provides a scaffold generator to generate a model class and a controller class and add scaffolding to the model class. The syntax of the scaffold generator class is as follows.

>ruby script/generate scaffold modelname, controllername,  action1, action2.. 

In the schema generator command, variable modelname specifies the model class and variable controllername specifies the controller class. Specifying controllername is optional. Action1, action2.. specify the actions in the controller class and are also optional. The following example generates a scaffolded model class, Catalog, and a controller class using the command:

>ruby script/generate scaffold catalog

This creates a model class and a controller class where the controller class created has the plural form of the model class. The model class is listed below with Model class Catalog extending the ActiveRecord::Base class:

class Catalog < ActiveRecord::Base

The controller class, CatalogsController, which extends the ApplicationController class, is listed below:

class CatalogsController < ApplicationController
  def index
    render :action => 'list'

  # GETs should be safe (see  http://www.w3.org/2001/tag/doc/whenToUseGet.html)
  verify :method => :post, :only => [ :destroy, :create, :update ],
         :redirect_to => { :action => :list }

  def list
    @catalog_pages, @catalogs = paginate :catalogs, :per_page => 10

  def show
    @catalog = Catalog.find(params[:id])

  def new
    @catalog = Catalog.new

  def create
    @catalog = Catalog.new(params[:catalog])
    if @catalog.save
      flash[:notice] = 'Catalog was successfully created.'
      redirect_to :action => 'list'
      render :action => 'new'

  def edit
    @catalog = Catalog.find(params[:id])

  def update
    @catalog = Catalog.find(params[:id])
    if @catalog.update_attributes(params[:catalog])
      flash[:notice] = 'Catalog was successfully updated.'
      redirect_to :action => 'show', :id => @catalog
      render :action => 'edit'

  def destroy
    redirect_to :action => 'list'

The default scaffolded actions and views that get generated are: index, list, show, new, create, edit, update, destroy.

Creating and Updating a Database Row

Next, we shall create and edit a catalog entry with the Rails MVC application. First, we start the Ruby web server WEBrick with the following command.

> ruby script/server

You can then access the web server with url http://localhost:3000:

Displays figure 1. WEBrick Web Server

You can display the list of catalog entries in the catalogs table by invoking the list action with url http://localhost:3000/catalogs/list:

Displays figure 2. Invoking the list action.

To create a new catalog entry, you click on the New catalog link. This invokes the new action. The view template corresponding to new action displays the catalog entry form. To create a new catalog entry, you specify field values and click on the Create button:

Displays figure 3. New Catalog Entry View.

This creates a new catalog entry and adds it to the list view:

Displays figure 4. List view with new row.

To edit a catalog entry, you click on the Edit link. In the edit view:modify a field value for example, you modify title, and click on the Edit button:

Displays figure 5. Edit view

The catalog entry gets modified as shown in show view:

Displays figure 6. show view.

You click on the Back button to display the list view with modified catalog entry:

Displays figure 7. Modified list view.

Congratulations! You have now created a MVC application with Ruby on Rails. You did not have to create any JSPs/HTMLs, Servlets, EJBs or configuration files so that the Ruby on Rails framework is providing you with increased ease of development.

Bridging the IT gap between rising business demands and ageing tools

More from The Register

next story
NO MORE ALL CAPS and other pleasures of Visual Studio 14
Unpicking a packed preview that breaks down ASP.NET
DARPA-derived secure microkernel goes open source tomorrow
Hacker-repelling, drone-protecting code will soon be yours to tweak as you see fit
Cheer up, Nokia fans. It can start making mobes again in 18 months
The real winner of the Nokia sale is *drumroll* ... Nokia
Put down that Oracle database patch: It could cost $23,000 per CPU
On-by-default INMEMORY tech a boon for developers ... as long as they can afford it
Google shows off new Chrome OS look
Athena springs full-grown from Chromium project's head
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
HIDDEN packet sniffer spy tech in MILLIONS of iPhones, iPads – expert
Don't panic though – Apple's backdoor is not wide open to all, guru tells us
prev story


Designing a Defense for Mobile Applications
Learn about the various considerations for defending mobile applications - from the application architecture itself to the myriad testing technologies.
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.
Top 8 considerations to enable and simplify mobility
In this whitepaper learn how to successfully add mobile capabilities simply and cost effectively.
Seven Steps to Software Security
Seven practical steps you can begin to take today to secure your applications and prevent the damages a successful cyber-attack can cause.
Boost IT visibility and business value
How building a great service catalog relieves pressure points and demonstrates the value of IT service management.