In-Depth

Use the Ruby on Rails Alternative

Take a more expedient approach for developing MVC Web applications than you might take using J2EE technologies.

Ruby on Rails is an open source Web framework for developing Model-View-Controller (MVC) Web applications that access databases. Ruby on Rails is based on the object-oriented Ruby scripting language. The model class in a Ruby on Rails application specifies the data model. A connection with the database is obtained in the model class, and the database table from which data is to be retrieved is specified. The controller class specifies the actions (methods) that contain the business logic to process data, and the view templates are the user interfaces (UIs) for the MVC application. Controller class methods are invoked from a view template, the controller class processes data using the model class, and it renders a view template or invokes another controller method.

Ruby on Rails doesn't require configuration files as does a Java 2 Platform, Enterprise Edition (J2EE) application. Ruby on Rails requires a Web server and a database, and it includes the WEBrick Web server. It is also preconfigured with the MySQL database. Let's look at how to use Ruby on Rails to develop a Create-Read-Update-Delete (CRUD) application. A CRUD application is used essentially to create, manipulate, and delete database table entries.

Because a Rails application is of the MVC pattern, the model and controller classes are Ruby classes (.rb files). The model class models data and extends the ActionRecord::Base class. Models provide object-relational mapping (ORM) between business objects and the database. The view templates are the UIs of a Ruby on Rails application and are represented with .rhtml or .rxml files. An RHTML view template is the more commonly used alternative and is Ruby-embedded HTML. The controller class extends the ActionController::Base class and specifies actions (methods) to process data. Ruby on Rails provides various commands to generate a Rails application and model and controller classes. Some Ruby on Rails commands are listed in Table 1.

Get On Track
Begin by installing Ruby on Rails and including RubyGems, the standard package manager used with Ruby applications and libraries. Here is the procedure to install Ruby on Rails:

  1. Download the Ruby Windows Installer application by double-clicking the ruby185-21.exe application to start the Ruby Setup Wizard. Click Next, and read and accept the license agreement.
  2. Select the default components to install, which include the RubyGems package manager, and click Next.
  3. Specify a directory to install Ruby (the default is c:/ruby), and click Next.
  4. Choose a Start Menu folder, and click Install to install Ruby and RubyGems.
  5. Install Rails by using the CD (change directory) command to make c:/ruby the current directory, and then run this command to install Rails and its dependencies—note that the activerecord package implements the model layer of a Rails MVC application, and the actionpack package implements the view and controller:
          gem install rails --include-
            dependencies 
    
  6. Use Setup.exe to download and install MySQL 5.0, and create a MySQL Server instance.

Now let's create a Ruby on Rails application that represents a journal catalog. Use the rails command on the command line to create a Ruby on Rails application in the catalog directory from within the ruby directory:

rails catalog

The app directory contains the subdirectories controllers, models, and view for the controller classes, model classes, and view templates, respectively. The config directory contains the database.yml file in which the database configuration is specified. A Rails application may be run in development (the default mode), test, or production mode.

For the example here let's run the Rails application in development mode. Modify the development mode settings in the database.yml file to specify the database as mysql. The development mode settings for the MySQL database should look like this:

development:  
adapter: mysql 
database: test  
username: root  
password: mysql 
host: localhost

The db directory is used for migration scripts, which will be discussed shortly.

Now we need to create a database table that will use ActiveRecord migrations. A migration class extends the ActiveRecord::Migration class and is run with the rake command. The rake command is similar to Ant's build tool for creating J2EE applications. A migration script gets created when a model class script is created. Create a model script with this command in the Ruby Console Window from the ruby/catalog directory:

ruby script/generate model catalog

The model class catalog.rb is created in the app/models directory, and the migration script 001_create_catalogs.rb is created in the db/migrate directory. The migration script class, CreateCatalogs, extends the ActiveRecord::Migration class:

class CreateCatalogs < 
  ActiveRecord::Migration
  def self.up
    create_table :catalogs do |t|
      # t.column :name, :string
    end
  end

  def self.down
    drop_table :catalogs
  end
end

The default migration script consists of the methods self.up and self.down. The self.up method is invoked to run a migration and create a database table. Use the create_table transformation of the ActiveRecord::Migration class to create a database table called catalogs. ActiveRecord uses pluralization to map a model class to a database table. The model class is singular and uppercase, and the database table is plural and lowercase.

In the Ruby on Rails application example the model class is Catalog and the database table is catalogs. The ActiveRecord::Migration class provides various transformations for a database. Some of the transformations are listed in Table 2.

Modify the migration script 001_create_catalogs.rb to create a database table, and then add data to the table. In the create_table transformation create a table called catalogs with the columns journal, publisher, edition, title, and author:

create_table :catalogs do |t|
  t.column :journal, :string, 
  :limit => 255
  t.column :publisher, :string, 
  :limit => 255
  t.column :edition, :string, 
  :limit => 255
  t.column :title, :string, 
  :limit => 255
  t.column :author, :string, 
  :limit => 255
  end

Valid column types are integer, float, datetime, date, timestamp, time, text, string binary, and boolean. Valid column options are limit, default, and null.

Next, add data to the table with the ActiveRecord::Base class method, create, to add a table row:

Catalog.create :journal => 
  "developerWorks", :publisher => 
  "IBM", 
  :edition => "September 2006", 
  :title=> 
  "A PHP V5 migration guide", 
  :author=>"Jack D. Herrington"

Listing 1 shows the complete migration script. Run the migration with the rake command from the /ruby/catalog directory. Rails has a target called migrate to run migrations:

rake db:migrate

The catalogs database table is created in the MySQL database named mysql. The catalogs table has a primary key field of type int(11) and the auto_increment attribute, which generates a unique identity for new rows.

Develop a CRUD Application
Before we develop a Ruby on Rails CRUD application, note that a Ruby on Rails application consists of these Ruby scripts and view templates:

  • Model class in the app/models directory
  • Controller class in the app/controllers directory
  • View templates (RHTML files) in the app/views directory

Previously we created a model class Ruby script. We use an interface to create new entries in the database, retrieve entries, update entries, and delete entries. The interface to the data in the database is scaffolding. Scaffolding consists of controller and model Ruby classes and view templates. Rails provides two types of scaffolding, dynamic scaffolding and scaffolding created with the ScaffoldGenerator. You can create a dynamic scaffolding by adding this scaffold method invocation to the controller class:

scaffold :modelname

The scaffold method generates controller logic and view templates dynamically using a model class obtained with Rails naming conventions. The first letter of the modelname is uppercase to obtain the model class. For example, if the modelname specified in the scaffold method is catalog, the Catalog model class is used in the scaffolding.

Instance variables @catalog/@catalogs are used in the controller class; controller instance variables are also available in the view templates. The Rails framework provides the scaffold generator to create a controller class, a model class, and the scaffolding for a CRUD application. Scaffolding generated with the ScaffoldGenerator is similar to the one generated with the scaffold method, except that the controller logic and view templates are generated when the ScaffoldGenerator command is run instead of being generated dynamically. In the Ruby console window run the scaffold generator:

ruby script/generate scaffold 
  catalog

This command generates a model class, a controller class, and the view templates index.rhtml, list.rhtml, show.rhtml, new.rhtml, create.rhtml, edit.rhtml, update.rhtml, and destroy.rhtml. The Catalog model class looks like this:

class Catalog > 
  ActiveRecord::Base
end

Listing 2 shows the controller class CatalogsController.

With the scaffolding these actions (methods) are generated in the controller class: index, list, show, new, create, edit, update, and destroy. The default view templates may be overridden with view templates in the views directory. For example, a custom view template edit.rhtml can be provided in the views/catalog directory.

Next, let's run the Ruby on Rails application in the WEBrick Web server. Begin by starting the WEBrick server from the /ruby/catalog directory:

ruby script/server

Access the WEBrick Web server with the URL, http://localhost:3000 (see Figure 1). Display the list of catalog entries with the list view template, which is invoked with the URL, http://localhost:3000/catalogs/list. To create a new catalog entry click the New catalog link (see Figure 2). In the new view template add a catalog entry, and click the Create button. A new catalog entry is added in the list view template. Click the Show link to show a catalog entry. To delete a catalog entry click the Destroy link, and to edit a catalog entry click the Edit link (see Figure 3).

Use the edit view template to modify the catalog entry; for example, modify the title and click the Edit button to update the catalog entry (see Figure 4).

Ruby on Rails is simpler than J2EE for developing MVC Web applications. The JavaServer Pages (JSP), HTML, servlets, Enterprise JavaBeans (EJB), and configuration fields that are required in a J2EE application are not required for a Ruby on Rails application.

About the Author

Deepak Vohra, a Sun-certified Java programmer and Sun-certified Web component developer, has published numerous articles in industry publications and journals. Deepak is the author of the book "Ruby on Rails for PHP and Java Developers."

comments powered by Disqus

Featured

  • Compare New GitHub Copilot Free Plan for Visual Studio/VS Code to Paid Plans

    The free plan restricts the number of completions, chat requests and access to AI models, being suitable for occasional users and small projects.

  • Diving Deep into .NET MAUI

    Ever since someone figured out that fiddling bits results in source code, developers have sought one codebase for all types of apps on all platforms, with Microsoft's latest attempt to further that effort being .NET MAUI.

  • Copilot AI Boosts Abound in New VS Code v1.96

    Microsoft improved on its new "Copilot Edit" functionality in the latest release of Visual Studio Code, v1.96, its open-source based code editor that has become the most popular in the world according to many surveys.

  • AdaBoost Regression Using C#

    Dr. James McCaffrey from Microsoft Research presents a complete end-to-end demonstration of the AdaBoost.R2 algorithm for regression problems (where the goal is to predict a single numeric value). The implementation follows the original source research paper closely, so you can use it as a guide for customization for specific scenarios.

  • Versioning and Documenting ASP.NET Core Services

    Building an API with ASP.NET Core is only half the job. If your API is going to live more than one release cycle, you're going to need to version it. If you have other people building clients for it, you're going to need to document it.

Subscribe on YouTube