- Reversible Migrations
- Assets Pipeline
Download – http://rubyonrails.org/download
Read more Rails 3.1.0 has been released!
Download – http://rubyonrails.org/download
Read more Rails 3.1.0 has been released!
This Ruby-based framework for rapid development uses a model-view-controller pattern
14 Jun 2005
Ruby on Rails is a recent entry into the world of Web application development that is rapidly gaining mindshare, even while still in beta versions. Rails succeeds by automating the creation of the most common types of Web applications while not straightjacketing you if you want to add custom or atypical requirements. Moreover, compared to many Free Software libraries that perform individual aspects of a Web application, Rails contains a nicely integrated set of tools for all aspects.
Ruby on Rails is taking Web development by storm. Let’s start with a refresher on the underlying technologies:
Being a full-stack framework means that all layers in Rails are built to work together so you don’t repeat yourself and can use a single language from top to bottom. Within Rails, everything (templates to control flow to business logic) is written in Ruby. Rails favors reflection and runtime extensions over configuration files and annotations.
This article details the components of Rails and shows you how it works.
The first thing to understand about Rails is its model/view/controller (MVC) architecture. While this approach is not unique to Rails — or even to Web applications as opposed to other programs — Rails provides a very clear and focused MVC way of thinking. If you stray from the MVC approach, Rails becomes far less useful than if you follow its paradigm.
The model part of a Rails application is primarily the underlying database it uses. In fact, in many ways a Rails application is just a way to perform manipulations on the data in a relational database management system (RDBMS) in a directed way.
A central component of Rails is the class
ActiveRecord, which maps relational tables to Ruby objects and thereby to the data manipulated by controllers and shown in views. Rails applications are particularly likely to use the ubiquitous MySQL database, but bindings exist for a number of other RDBMSs, including IBMÂ® DB2Â®.
If you like, you can add Ruby code to perform extra validation within an application model, enforce data relationships, or trigger other actions. The Ruby files within an application’s app/models/ directory can call a variety of validation methods of
ActiveRecord. However, you can also leave the model code as a stub as well and rely only on the constraints of the RDBMS that holds the data. For example, the application I develop in this example contains only this skeleton model code (at least initially):
class Contact < ActiveRecord::Base end
Controllers carry out your application logic in its abstract form. That is, the Ruby scripts in an application’s app/controllers/ directory will load model data into variables, save it back, and massage and manipulate it. But controllers are not concerned with how the data is concretely presented and entered by users. In the general MVC paradigm, this can allow the user multiple styles of interaction with the same controller: a native GUI, a Web interface, and a speech interface for the visually impaired might all interact with the same controller.
Rails is not quite so general as that, though; instead, it is more narrowly focused on providing and collecting data within Web pages. Nonetheless, you can modify the layout of those Web pages — colors, fonts, tables, stylesheets, etc. — independently of controller code.
Rails views are where we leave Ruby code. Rails contains a very nice template language for .rhtml files that combines pure HTML with embedded Ruby code. The very surface appearance of a Rails application screen is generally controlled by CSS stylesheets. The .rhtml format is an enhancement of HTML. Actually, a simple HTML file by itself is also a valid RHTML template, but there is not much point in omitting the scripting control that RHTML gives you.
RHTML is a true template format — not simply a way of embedding code in HTML — and this is a much more powerful approach. If you’re familiar with PHP, think of the contrast between PHP itself and Smarty templates. That is, embedded scripting just intermixes code with uninterpreted HTML; the code portion is still responsible for issuing
In contrast, a template engine adds a custom set of tags to HTML that allows you to express conditions, loops, and other logic as part of the enhanced HTML markup.
The tools that Rails provides are basically a set of code generators. I like this approach much better than that of a development environment that forces me to use a rigid workspace and IDE. Rails does not get in your way, but nonetheless saves most of the work of manual programming — or at least eases you into the parts that require manual coding by providing first-pass scaffolding “for free.”
The concept of scaffolding is a central notion in Rails. Very simple applications can almost entirely avoid custom coding by letting Rails dynamically generate client HTML pages as it runs. A first pass at code generation creates just the raw scaffolding; you can subsequently generate more specific controllers, views, and models that you can customize. But you need not generate much to get started.
Rails relies on a fixed and fairly common-sense organization of its files, but this organization is relatively rigid. You will just be picking a fight with the Rails environment if you try to force other file and code organizations. Then again, I cannot see a reason not to go along with the organization Rails provides; for the most part, it “fits your brain” (as Ruby fans like to say). For example, the directory names and their organization are probably pretty darn close to what you would choose if you were designing a framework from scratch (at least if you think in the “Ruby way”).
There are a couple things to notice in this first table. Of central importance is that every table must have an
Another little oddity exists with the Rails’ use of singular and plural names for various things. Various items are renamed between singular and plural versions depending on their usage and context. Table names should use the plural form. I have not experimented with words having irregular plurals; words like
Now that you have a database to interact with, create the
I have abridged the output from running
Having created the AddressBook/ directory and needed children, you need to perform just a bare initial configuration. First, set the database by modifying a YAML configuration file like so:
Finally, you need to serve the data. Rails comes with its own single-function Web server, WEBrick, which is perfectly good for our experiment. You might also follow instructions at the Ruby on Rails Web site to configure Apache or other servers to serve Rails applications via FCGI (or plain CGI, but plain CGI will be slow).
The prior steps are enough to let you view a welcome splash page on the WEBrick port. For example, on my local system, I can now view
Notice here that you should use the singular
Now you need to edit one more generated file, just a bit, to get the controller to use the scaffold:
Now you can view and modify the contents of your database at a URL like
The previous code creates a fully working interface to view and modify your database, but all the formatting, presentation, and business logic (such as there is) are done dynamically by Rails without any great sophistication. In order to create something a bit more custom, you need to generate a bit more code. What we need now is for Rails to explicitly write out all the scaffolding it is implicitly generating on the fly so that we can tinker with it.
Now there’s a bit more to work with, so try modifying a few things. (Notice that this code has gone back to the plural form
Now that you have the code, what does
As promised, a controller’s main job is to load data into variables. The object
The controller in this example ultimately connects to views, RHTML files that make use of the data values loaded into variables by the controller. For example, here’s part of the
The initial model contained only a name for a contact. Unfortunately, I don’t have room in this article to expand the model to include actual contact data like phone numbers, addresses, emails, etc. In general, that data would live in a child table with a foreign key relation to the table
Before wrapping up, let’s change the data model just slightly and see how that affects the application. First, add a column:
Now that you’ve changed the underlying model,
So what does your hand-tweaked application look like? Not a lot different from the default, but you can see your modifications in action in Figures 3 and 4:
Rails gives you an extremely quick way to develop flexible Web applications; this introduction just barely touched on what it’s like to work with Rails. The full framework contains many useful classes and methods for carrying out the actions most used in Web-based applications.
The best thing about Rails is that it fosters a whole “Rails way of thinking,” since it comes complete with all the supporting code you need. This is a big plus over other toolkits and frameworks that just give raw materials to work with. Rails development offers you a clear path from a half-formed idea to a fully functioning Web application.