Feeds

Ruby on Rails Part 2

Here goes

Beginner's guide to SSL certificates

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:

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

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:

Catalog.delete(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:

:action=>:index

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:

@section=params[:section] 

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
end

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
scaffold:catalog
end

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
end

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
end

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

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


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

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

  def new
    @catalog = Catalog.new
  end

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

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

  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
    else
      render :action => 'edit'
    end
  end

  def destroy
    Catalog.find(params[:id]).destroy
    redirect_to :action => 'list'
  end
end

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.

Intelligent flash storage arrays

More from The Register

next story
Be real, Apple: In-app goodie grab games AREN'T FREE – EU
Cupertino stands down after Euro legal threats
Download alert: Nearly ALL top 100 Android, iOS paid apps hacked
Attack of the Clones? Yeah, but much, much scarier – report
You stupid BRICK! PCs running Avast AV can't handle Windows fixes
Fix issued, fingers pointed, forums in flames
Microsoft: Your Linux Docker containers are now OURS to command
New tool lets admins wrangle Linux apps from Windows
Bada-Bing! Mozilla flips Firefox to YAHOO! for search
Microsoft system will be the default for browser in US until 2020
Facebook, working on Facebook at Work, works on Facebook. At Work
You don't want your cat or drunk pics at the office
Soz, web devs: Google snatches its Wallet off the table
Killing off web service in 3 months... but app-happy bonkers are fine
prev story

Whitepapers

Why cloud backup?
Combining the latest advancements in disk-based backup with secure, integrated, cloud technologies offer organizations fast and assured recovery of their critical enterprise data.
Forging a new future with identity relationship management
Learn about ForgeRock's next generation IRM platform and how it is designed to empower CEOS's and enterprises to engage with consumers.
How to determine if cloud backup is right for your servers
Two key factors, technical feasibility and TCO economics, that backup and IT operations managers should consider when assessing cloud backup.
Reg Reader Research: SaaS based Email and Office Productivity Tools
Read this Reg reader report which provides advice and guidance for SMBs towards the use of SaaS based email and Office productivity tools.
Getting ahead of the compliance curve
Learn about new services that make it easy to discover and manage certificates across the enterprise and how to get ahead of the compliance curve.