Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / Ruby

What is Ruby on Rails? (An introduction)

4.51/5 (21 votes)
12 Jan 2012CPOL6 min read 49.8K  
An introduction to the Ruby on Rails framework.
  1. Ruby (the programming language)
  2. Rails (the framework)
  3. MVC (Model-View-Controller)
  4. Routing
  5. ActiveRecord
  6. Database migrations
  7. Separation of environments (development, production, etc.)
  8. Assets management (images, stylesheets, and JavaScript)
  9. Plug-ins (RubyGems, etc.)
  10. Conclusion
  11. More information

So what is Ruby on Rails? Here's an introduction.

Ruby (the programming language)

From Wikipedia: "Ruby is a dynamic, reflective, general-purpose object-oriented programming language that combines syntax inspired by Perl with Smalltalk-like features. Ruby originated in Japan during the mid-1990s and was first developed and designed by Yukihiro "Matz" Matsumoto. It was influenced primarily by Perl, Smalltalk, Eiffel, and Lisp." Ruby is a beautiful language – you'll love it. Read more on ruby-lang.org and try it here.

Rails (the framework)

Rails is a web framework built on Ruby, hence the name Ruby on Rails. It enables the programmer to easily create advanced database-driven websites using scaffolding and code generation, following convention over configuration, which means that if you stick to a certain set of conventions, a lot of features will work right out of the box with very little code.

MVC (Model-View-Controller)

Rails is based on a programming pattern called MVC, which stands for Model-View-Controller. Here I'll try to explain what it is and why it makes sense to use it.

Model

The model in MVC is a class for each entity in your application. Example models are User, Category, or Product. The models hold all business logic, for example what should happen if you delete a product, add a new category, or create a new user.

See the ActiveRecord section for example models.

View

The views in MVC hold all your presentation and presentation logic, normally HTML. It is based on ERuby which is a templating system that allows for Ruby embedded into HTML and other languages. You probably know this kind of templating system from ASP, PHP, or JSP.

Example view:

XML
<h1><%= @user.name %></h1>
<p>
  <%= @user.description %>
</p>

Controller

The controller is what binds together the models and views, for example tells the show product view which product it should show, or handles the data from a form post when a user updates a shopping basket.

Example controller:

Ruby
class SiteController < ApplicationController
  def home
  end

  def about
  end
end

Why does MVC make sense?

MVC allows for perfect separation of business logic from presentation logic, giving you a much cleaner application that is easier to maintain and, on top of that, a lot more fun to develop.

Routing

So, how is a request from a visitor's browser sent down to the controller that handles this request? This is done by a routing engine that interprets the request and passes it on to the matching controller:

Ruby
match 'about' => 'site#about'      # => /about
match 'contact' => 'site#contact'  # => /contact
root :to => 'site#home'            # => /

CRUD (Create, Read, Update, Delete)

In the heart of the Rails routing engine lies CRUD, or Create, Read, Update, Delete, which comes from a notion that all web pages are made up of these four actions. For example, you create a product, view, or read a user, edit, or update a category, and delete an order.

If you follow this pattern, you'll get a lot of work done for you. For example, all it takes to create all of these actions for a product is to tell the routing engine that you have an entity called product, and it will wire up all the routing logic that binds the request to the matching controller for you:

Ruby
resources :products  # => /products/23
resources :orders do # => /orders/124
  resources :items   # => /orders/124/items
end

ActiveRecord

ActiveRecord is a pattern that allows for all database access to be written without a single line of database access. You tell the class, or model, what kind of entity you want it to be, which relations it has, and it automagically does the rest for you, creating properties based on the fields from the database, giving you database operation methods like create, update, and delete for free. You write only your custom business logic. The ActiveRecord classes are almost always what makes up the Model part of the aforementioned MVC pattern.

Example ActiveRecord model:

Ruby
class Order < ActiveRecord::Base
  belongs_to :user
  has_many :items
end

Then you can:

Ruby
order = Order.find(123)
order.user.name # => user name
order.items     # => array of items

Database migrations

In Ruby on Rails, you almost never talk directly to your database like you know it from PHP or other scripting languages. Instead, as part of ActiveRecord, comes a complete database migration framework. Database migrations mean that, instead of manually editing your database, you create Ruby code for creating tables and adding columns. What this does is that it allows for migrating multiple databases with the same changes, for example, a development and production database, without having to remember what changes you made in your development database when deploying to production – you just run the same migrations in a different environment.

Migrations are also created using code generation, so you can create a table or add a column using a single shell command:

Ruby
# creates a 'users' table with the specified fields
rails generate model User name:string email:string age:integer

# adds a description field to the 'users' table
rails generate migration AddDescriptionToUsers description:text

# runs the migration
rake db:migrate

Separation of environments (development, production, etc.)

In Rails, you have a perfect separation of environments. This means that you can run your system with different settings based on which environment you are currently in, for example, you want your development environment to display verbose error messages where your production site shows a user friendly message to the end user.

Assets management (images, stylesheets, and JavaScript)

The Rails 3.1 assets pipeline allows for all your assets (images, stylesheets, and JavaScript) to be managed for you. In your development environment you have your full folder structure with stylesheets and JavaScript written in different languages like CoffeeScript and SCSS. When you deploy, all your assets are compiled and fetched from the same folder, all stylesheets compiled together, the same with your JavaScript. This also means that you don't have to include, for example, jQuery – this is included for you via the jQuery Rails plug-in.

Plug-ins (RubyGems, etc.)

Coding in Ruby on Rails means that you get a butt load of plug-ins already written for you. Not in the Rails core (it's very clean) but as RubyGems which is a kind of packaging for Ruby. For example, you could have plug-ins for pagination, search engine optimization, or image processing. As of the time of writing, there are over 27,000 RubyGems to be used for free.

Examples of installing plug-ins:

gem 'will_paginate'    # installs a pagination plugin
gem 'dynamic_sitemaps' # installs a sitemap generation plugin

Conclusion

Ruby on Rails is a great framework for creating advanced web applications writing very little code in comparison to what you get. I recommend it for almost any kind of application, and especially for prototyping. To inspire you, I created a video where I create a blog in 10 minutes using Ruby on Rails. Check it out and be sold. I also recommend the documentation section of the official Ruby on Rails site. For those of you used to Ruby on Rails, I recommend this blog post about the changes from version 3.0 to version 3.1.

More information

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)