Home > Articles > Programming > Ruby

This chapter is from the book

1.2 Up and Running

It's time now to get going with a Ruby on Rails development environment and our first application. There is quite a bit of overhead here, especially if you don't have extensive programming experience, so don't get discouraged if it takes a while to get started. It's not just you; every developer goes through it (often more than once), but rest assured that the effort will be richly rewarded.

1.2.1 Development Environments

Considering various idiosyncratic customizations, there are probably as many development environments as there are Rails programmers, but there are at least two broad themes: text editor/command line environments, and integrated development environments (IDEs). Let's consider the latter first.


There is no shortage of Rails IDEs; indeed, the main Ruby on Rails site names four: RadRails, RubyMine, 3rd Rail, and NetBeans. All are cross-platform, and I've heard good things about several of them. I encourage you to try them and see if they work for you, but I have a confession to make: I have never found an IDE that met all my Rails development needs—and for some projects I haven't even been able to get them to work at all.

Text Editors and Command Lines

What are we to use to develop Rails apps, if not some awesome all-in-one IDE? I'd guess the majority of Rails developers opt for the same solution I've chosen: use a text editor to edit text, and a command line to issue commands (Figure 1.1). Which combination you use depends on your tastes and your platform:

Figure 1.1

Figure 1.1 A text editor/command line development environment (TextMate/iTerm).

  • Macintosh OS X: Like many Rails developers, I prefer TextMate. Other options include Emacs and MacVim (launched with the command macvim ), the excellent Macintosh version of Vim.7 I use iTerm for my command line terminal; others prefer the native Terminal app.
  • Linux: Your editor options are basically the same as OS X, minus TextMate. I'd recommend graphical Vim (gVim), gedit (with the GMate plugins), or Kate. As far as command lines go, you're totally set: every Linux distribution comes with at least one command line terminal application (and often several).
  • Windows: Unfortunately, I can't make any personal recommendations here, but you can do what I did: drop "rails windows" into Google to see what the latest thinking is on setting up a Rails development environment on Windows. Two combinations look especially promising: Vim for Windows with Console (recommended by Akita On Rails) or the E Text Editor with Console and Cygwin (recommended by Ben Kittrell). Rails Tutorial readers have suggested looking at Komodo Edit (cross-platform) and the Sublime Text editor (Windows only) as well. No matter which editor you choose, I recommend trying Cygwin, which provides the equivalent of a Unix terminal under Windows; see, for example, this video on Ruby on Rails + Cygwin + Windows Vista. (In addition to installing the packages in the video, I recommend installing git, curl, and vim. Don't install Rails as in the video, though; use the instructions below instead.) With Cygwin, most of the command-line examples in the book should work with minimum modification.

If you go with some flavor of Vim, be sure to tap into the thriving community of Vim-using Rails hackers. See especially the rails.vim enhancements and the NERD tree project drawer.


Although there are many web browsers to choose from, the vast majority of Rails programmers use Firefox, Safari, or Chrome when developing. The screenshots in Rails Tutorial will generally be of a Firefox browser. If you use Firefox, I suggest using the Firebug add-on, which lets you perform all sorts of magic, such as dynamically inspecting (and even editing) the HTML structure and CSS rules on any page. For those not using Firefox, Firebug Lite works with most other browsers, and both Safari and Chrome have a built-in "Inspect element" feature available by right-clicking on any part of the page. Regardless of which browser you use, experience shows that the time spent learning such a web inspector tool will be richly rewarded.

A Note About Tools

In the process of getting your development environment up and running, you may find that you spend a lot of time getting everything just right. The learning process for editors and IDEs is particularly long; you can spend weeks on TextMate or Vim tutorials alone. If you're new to this game, I want to assure you that spending time learning tools is normal. Everyone goes through it. Sometimes it is frustrating, and it's easy to get impatient when you have an awesome web app in your head and you just want to learn Rails already, but have to spend a week learning some weird ancient Unix editor just to get started. But a craftsman has to know his tools; in the end the reward is worth the effort.

1.2.2 Ruby, RubyGems, Rails, and Git

Now it's time to install Ruby and Rails. The canonical up-to-date source for this step is the Ruby on Rails download page. I'll assume you can go there now; parts of this book can be read profitably offline, but not this part. I'll just inject some of my own comments on the steps.

Install Git

Much of the Rails ecosystem depends in one way or another on a version control system called Git (covered in more detail in Section 1.3). Because its use is ubiquitous, you should install Git even at this early stage; I suggest following the installation instructions for your platform at the Installing Git section of Pro Git.

Install Ruby

The next step is to install Ruby. It's possible that your system already has it; try running

$ ruby -v
ruby 1.9.2

to see the version number. Rails 3 requires Ruby 1.8.7 or later and works best with Ruby 1.9.2. This tutorial assumes that you are using the latest development version of Ruby 1.9.2, known as Ruby 1.9.2-head, but Ruby 1.8.7 should work as well.

The Ruby 1.9 branch is under heavy development, so unfortunately installing the latest Ruby can be quite a challenge. You will likely have to rely on the web for the most up-to-date instructions. What follows is a series of steps that I've gotten to work on my system (Macintosh OS X), but you may have to search around for steps that work on your system.

As part of installing Ruby, if you are using OS X or Linux I strongly recommend installing Ruby using Ruby Version Manager (RVM), which allows you to install and manage multiple versions of Ruby on the same machine. (The Pik project accomplishes a similar feat on Windows.) This is particularly important if you want to run Rails 3 and Rails 2.3 on the same machine. If you want to go this route, I suggest using RVM to install two Ruby/Rails combinations: Ruby 1.8.7/Rails 2.3.10 and Ruby 1.9.2/Rails 3.0.1. If you run into any problems with RVM, you can often find its creator, Wayne E. Seguin, on the RVM IRC channel (#rvm on freenode.net).8

After installing RVM, you can install Ruby as follows:9

$ rvm update --head
$ rvm reload
$ rvm install 1.8.7
$ rvm install 1.9.2
<wait a while>

Here the first two commands update and reloadRVMitself, which is a good practice since RVMgets updated frequently. The final two commands do the actual Ruby installations; depending on your system, they might take a while to download and compile, so don't worry if it seems to be taking forever. (Also beware that lots of little things can go wrong. For example, on my system the latest version of Ruby 1.8.7 won't compile; instead, after much searching and hand-wringing, I discovered that I needed "patchlevel" number 174:

$ rvm install 1.8.7-p174

When things like this happen to you, it's always frustrating, but at least you know that it happens to everyone. . . )

Ruby programs are typically distributed via gems, which are self-contained packages of Ruby code. Since gems with different version numbers sometimes conflict, it is often convenient to create separate gemsets, which are self-contained bundles of gems. In particular, Rails is distributed as a gem, and there are conflicts between Rails 2 and Rails 3, so if you want to run multiple versions of Rails on the same system you need to create a separate gemset for each:

$ rvm --create 1.8.7-p174@rails2tutorial
$ rvm --create use 1.9.2@rails3tutorial

Here the first command creates the gemset rails2tutorial associated with Ruby 1.8.7-p174, while the second command creates the gemset rails3tutorial associated with Ruby 1.9.2 and uses it (via the use command) at the same time. RVM supports a large variety of commands for manipulating gemsets; see the documentation at http://rvm.beginrescueend.com/gemsets/.

In this tutorial, we want our system to use Ruby 1.9.2 and Rails 3.0 by default, which we can arrange as follows:

$ rvm --default use 1.9.2@rails3tutorial

This simultaneously sets the default Ruby to 1.9.2 and the default gemset to rails3-tutorial .

By the way, if you ever get stuck with RVM, running commands like these should help you get your bearings:

$ rvm --help
$ rvm gemset --help

Install RubyGems

RubyGems is a package manager for Ruby projects, and there are tons of great libraries (including Rails) available as Ruby packages, or gems. Installing RubyGems should be easy once you install Ruby. In fact, if you have installed RVM, you already have RubyGems, since RVM includes it automatically:

$ which gem

If you don't already have it, you should download RubyGems, extract it, and then go to the rubygems directory and run the setup program:

$ [sudo] ruby setup.rb

Here sudo executes the command ruby setup.rb as an administrative user, which has access to files and directories that normal users can't touch; I have put it in brackets to indicate that using sudo may or may not be necessary for your particular system. Most Unix/Linux/OS X systems require sudo by default, unless you are using RVM as suggested in Section 1.2.2. Note that you should not actually type any brackets; you should run either

$ sudo ruby setup.rb


$ ruby setup.rb

depending on your system.

If you already have RubyGems installed, you might want to update your system to the latest version:

$ [sudo] gem update --system

Finally, if you're using Ubuntu Linux, you might want to take a look at the Ubuntu/Rails 3.0 blog post by Toran Billups for full installation instructions.

Install Rails

Once you've installed RubyGems, installing Rails 3.0 should be easy:

$ [sudo] gem install rails --version 3.0.1

To verify that this worked, run the following command:

$ rails -v
Rails 3.0.1

1.2.3 The First Application

Virtually all Rails applications start the same way, with the rails command. This handy program creates a skeleton Rails application in a directory of your choice. To get started, make a directory for your Rails projects and then run the rails command to make the first application:

Listing 1.1. Running the rails script to generate a new application.

   $ mkdir rails_projects
$ cd rails_projects
$ rails new first_app
      create  README
      create  .gitignore
      create  Rakefile
      create  config.ru
      create  Gemfile
      create  app
      create  app/controllers/application_controller.rb
      create  app/helpers/application_helper.rb
      create  app/views/layouts/application.html.erb
      create  app/models
      create  config
      create  config/routes.rb
      create  config/application.rb
      create  config/environment.rb

Notice how many files and directories the rails command creates. This standard directory and file structure (Figure 1.2) is one of the many advantages of Rails; it immediately gets you from zero to a functional (if minimal) application. Moreover, since the structure is common to all Rails apps, you can immediately get your bearings when looking at someone else's code. A summary of the default Rails files appears in Table 1.1; we'll learn about most of these files and directories throughout the rest of this book.

Figure 1.2

Figure 1.2 The directory structure for a newly hatched Rails app.

Table 1.1. A summary of the default Rails directory structure




Core application (app) code, including models, views, controllers, and helpers


Application configuration


Files to manipulate the database


Documentation for the application


Library modules


Application log files


Data accessible to the public (e.g., web browsers), such as images and cascading style sheets (CSS)


A script provided by Rails for generating code, opening console sessions, or starting a local web server


Application tests (made obsolete by the spec/ directory in Section 3.1.2)


Temporary files


Third-party code such as plugins and gems


A brief description of the application


Utility tasks available via the rake command


Gem requirements for this app


A configuration file for Rack middleware


Patterns for files that should be ignored by Git

1.2.4 Bundler

After creating a new Rails application, the next step is to use Bundler to install and include the gems needed by the app. This involves opening the Gemfile with your favorite text editor:

$ cd first_app/
$ mate Gemfile

The result should look something like Listing 1.2.

Listing 1.2. The default Gemfile in the first_app directory.

source 'http://rubygems.org'

gem 'rails', '3.0.1'

# Bundle edge Rails instead:

   # gem 'rails', :git => 'git://github.com/rails/rails.git'

gem 'sqlite3-ruby', :require => 'sqlite3'

# Use unicorn as the web server

   # gem 'unicorn'

   # Deploy with Capistrano

   # gem 'capistrano'

   # To use debugger

   # gem 'ruby-debug'

   # Bundle the extra gems:

   # gem 'bj'

   # gem 'nokogiri', '1.4.1'

   # gem 'sqlite3-ruby', :require => 'sqlite3'

   # gem 'aws-s3', :require => 'aws/s3'

   # Bundle gems for certain environments:

   # gem 'rspec', :group => :test

   # group :test do

   #   gem 'webrat'

   # end

Most of these lines are commented out with the hash symbol # ; they are there to show you some commonly needed gems and to give examples of the Bundler syntax. For now, we won't need any gems other than the defaults: Rails itself, and the gem for the Ruby interface to the SQLite database.

Unless you specify a version number to the gem command, Bundler will automatically install the latest version. Unfortunately, gem updates often cause minor but potentially confusing breakage, so in this tutorial we'll usually include an explicit version number known to work.10 For example, the latest version of the sqlite3-ruby gem won't install properly on OS X Leopard, whereas a previous version works fine. Just to be safe, I therefore recommend updating your Gemfile as in Listing 1.3.

Listing 1.3. A Gemfile with an explicit version of the sqlite3-ruby gem.

source 'http://rubygems.org'

gem 'rails', '3.0.1'
gem 'sqlite3-ruby', '1.2.5', :require => 'sqlite3'

This changes the line

gem 'sqlite3-ruby', :require => 'sqlite3'

from Listing 1.2 to

gem 'sqlite3-ruby', '1.2.5', :require => 'sqlite3'

which forces Bundler to install version 1.2.5 of the sqlite3-ruby gem. (I've also taken the liberty of omitting the commented-out lines.) Note that I need version 1.2.5 of the sqlite3-ruby gem on my system, but you should try version 1.3.1 if 1.2.5 doesn't work on your system.

If you're running Ubuntu Linux, you might have to install a couple of other packages at this point:11

$ sudo apt-get install libxslt-dev libxml2-dev      # Linux only

Once you've assembled the proper Gemfile, install the gems using bundle install:

$ bundle install
Fetching source index for http://rubygems.org/

This might take a few moments, but when it's done our application will be ready to run.

1.2.5 rails server

Thanks to running rails new in Section 1.2.3 and bundle install in Section 1.2.4, we already have an application we can run—but how? Happily, Rails comes with a command-line program, or script, that runs a local web server,12 visible only from your development machine:13

$ rails server
=> Booting WEBrick
=> Rails 3.0.1 application starting on
=> Call with -d to detach
=> Ctrl-C to shutdown server

This tells us that the application is running on port number 300014 at the address This special address means that any computer on the local network can view our application; in particular, the machine running the development server—i.e., the local development machine—can view the application using the address localhost:3000.15 We can see the result of visiting http://localhost:3000/ in Figure 1.3.

Figure 1.3

Figure 1.3 The default Rails page (http://localhost:3000/.)

To see information about our first application, click on the link "About your application's environment". The result is shown in Figure 1.4.16

Figure 1.4

Figure 1.4 The default page (http://localhost:3000/) with the app environment.

Of course, we don't need the default Rails page in the long run, but it's nice to see it working for now. We'll remove the default page (and replace it with a custom home page) in Section 5.2.2.

1.2.6 Model-View-Controller (MVC)

Even at this early stage, it's helpful to get a high-level overview of how Rails applications work (Figure 1.5). You might have noticed that the standard Rails application structure (Figure 1.2) has an application directory called app/ with three subdirectories: models , views , and controllers . This is a hint that Rails follows the model-view-controller (MVC) architectural pattern, which enforces a separation between "domain logic" (also called "business logic") from the input and presentation logic associated with a graphical user interface (GUI). In the case of web applications, the "domain logic" typically consists of data models for things like users, articles, and products, and the GUI is just a web page in a web browser.

Figure 1.5

Figure 1.5 A schematic representation of the model-view-controller (MVC) architecture.

When interacting with a Rails application, a browser sends a request, which is received by a web server and passed on to a Rails controller, which is in charge of what to do next. In some cases, the controller will immediately render a view, which is a template that gets converted to HTML and sent back to the browser. More commonly for dynamic sites, the controller interacts with a model, which is a Ruby object that represents an element of the site (such as a user) and is in charge of communicating with the database. After invoking the model, the controller then renders the view and returns the complete web page to the browser as HTML.

If this discussion seems a bit abstract right now, worry not; we'll refer back to this section frequently. In addition, Section 2.2.2 has a more detailed discussion of MVC in the context of the demo app. Finally, the sample app will use all aspects of MVC; we'll cover controllers and views starting in Section 3.1.2, models starting in Section 6.1, and we'll see all three working together in Section 6.3.2.

InformIT Promotional Mailings & Special Offers

I would like to receive exclusive offers and hear about products from InformIT and its family of brands. I can unsubscribe at any time.


Pearson Education, Inc., 221 River Street, Hoboken, New Jersey 07030, (Pearson) presents this site to provide information about products and services that can be purchased through this site.

This privacy notice provides an overview of our commitment to privacy and describes how we collect, protect, use and share personal information collected through this site. Please note that other Pearson websites and online products and services have their own separate privacy policies.

Collection and Use of Information

To conduct business and deliver products and services, Pearson collects and uses personal information in several ways in connection with this site, including:

Questions and Inquiries

For inquiries and questions, we collect the inquiry or question, together with name, contact details (email address, phone number and mailing address) and any other additional information voluntarily submitted to us through a Contact Us form or an email. We use this information to address the inquiry and respond to the question.

Online Store

For orders and purchases placed through our online store on this site, we collect order details, name, institution name and address (if applicable), email address, phone number, shipping and billing addresses, credit/debit card information, shipping options and any instructions. We use this information to complete transactions, fulfill orders, communicate with individuals placing orders or visiting the online store, and for related purposes.


Pearson may offer opportunities to provide feedback or participate in surveys, including surveys evaluating Pearson products, services or sites. Participation is voluntary. Pearson collects information requested in the survey questions and uses the information to evaluate, support, maintain and improve products, services or sites, develop new products and services, conduct educational research and for other purposes specified in the survey.

Contests and Drawings

Occasionally, we may sponsor a contest or drawing. Participation is optional. Pearson collects name, contact information and other information specified on the entry form for the contest or drawing to conduct the contest or drawing. Pearson may collect additional personal information from the winners of a contest or drawing in order to award the prize and for tax reporting purposes, as required by law.


If you have elected to receive email newsletters or promotional mailings and special offers but want to unsubscribe, simply email information@informit.com.

Service Announcements

On rare occasions it is necessary to send out a strictly service related announcement. For instance, if our service is temporarily suspended for maintenance we might send users an email. Generally, users may not opt-out of these communications, though they can deactivate their account information. However, these communications are not promotional in nature.

Customer Service

We communicate with users on a regular basis to provide requested services and in regard to issues relating to their account we reply via email or phone in accordance with the users' wishes when a user submits their information through our Contact Us form.

Other Collection and Use of Information

Application and System Logs

Pearson automatically collects log data to help ensure the delivery, availability and security of this site. Log data may include technical information about how a user or visitor connected to this site, such as browser type, type of computer/device, operating system, internet service provider and IP address. We use this information for support purposes and to monitor the health of the site, identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents and appropriately scale computing resources.

Web Analytics

Pearson may use third party web trend analytical services, including Google Analytics, to collect visitor information, such as IP addresses, browser types, referring pages, pages visited and time spent on a particular site. While these analytical services collect and report information on an anonymous basis, they may use cookies to gather web trend information. The information gathered may enable Pearson (but not the third party web trend services) to link information with application and system log data. Pearson uses this information for system administration and to identify problems, improve service, detect unauthorized access and fraudulent activity, prevent and respond to security incidents, appropriately scale computing resources and otherwise support and deliver this site and its services.

Cookies and Related Technologies

This site uses cookies and similar technologies to personalize content, measure traffic patterns, control security, track use and access of information on this site, and provide interest-based messages and advertising. Users can manage and block the use of cookies through their browser. Disabling or blocking certain cookies may limit the functionality of this site.

Do Not Track

This site currently does not respond to Do Not Track signals.


Pearson uses appropriate physical, administrative and technical security measures to protect personal information from unauthorized access, use and disclosure.


This site is not directed to children under the age of 13.


Pearson may send or direct marketing communications to users, provided that

  • Pearson will not use personal information collected or processed as a K-12 school service provider for the purpose of directed or targeted advertising.
  • Such marketing is consistent with applicable law and Pearson's legal obligations.
  • Pearson will not knowingly direct or send marketing communications to an individual who has expressed a preference not to receive marketing.
  • Where required by applicable law, express or implied consent to marketing exists and has not been withdrawn.

Pearson may provide personal information to a third party service provider on a restricted basis to provide marketing solely on behalf of Pearson or an affiliate or customer for whom Pearson is a service provider. Marketing preferences may be changed at any time.

Correcting/Updating Personal Information

If a user's personally identifiable information changes (such as your postal address or email address), we provide a way to correct or update that user's personal data provided to us. This can be done on the Account page. If a user no longer desires our service and desires to delete his or her account, please contact us at customer-service@informit.com and we will process the deletion of a user's account.


Users can always make an informed choice as to whether they should proceed with certain services offered by InformIT. If you choose to remove yourself from our mailing list(s) simply visit the following page and uncheck any communication you no longer want to receive: www.informit.com/u.aspx.

Sale of Personal Information

Pearson does not rent or sell personal information in exchange for any payment of money.

While Pearson does not sell personal information, as defined in Nevada law, Nevada residents may email a request for no sale of their personal information to NevadaDesignatedRequest@pearson.com.

Supplemental Privacy Statement for California Residents

California residents should read our Supplemental privacy statement for California residents in conjunction with this Privacy Notice. The Supplemental privacy statement for California residents explains Pearson's commitment to comply with California law and applies to personal information of California residents collected in connection with this site and the Services.

Sharing and Disclosure

Pearson may disclose personal information, as follows:

  • As required by law.
  • With the consent of the individual (or their parent, if the individual is a minor)
  • In response to a subpoena, court order or legal process, to the extent permitted or required by law
  • To protect the security and safety of individuals, data, assets and systems, consistent with applicable law
  • In connection the sale, joint venture or other transfer of some or all of its company or assets, subject to the provisions of this Privacy Notice
  • To investigate or address actual or suspected fraud or other illegal activities
  • To exercise its legal rights, including enforcement of the Terms of Use for this site or another contract
  • To affiliated Pearson companies and other companies and organizations who perform work for Pearson and are obligated to protect the privacy of personal information consistent with this Privacy Notice
  • To a school, organization, company or government agency, where Pearson collects or processes the personal information in a school setting or on behalf of such organization, company or government agency.


This web site contains links to other sites. Please be aware that we are not responsible for the privacy practices of such other sites. We encourage our users to be aware when they leave our site and to read the privacy statements of each and every web site that collects Personal Information. This privacy statement applies solely to information collected by this web site.

Requests and Contact

Please contact us about this Privacy Notice or if you have any requests or questions relating to the privacy of your personal information.

Changes to this Privacy Notice

We may revise this Privacy Notice through an updated posting. We will identify the effective date of the revision in the posting. Often, updates are made to provide greater clarity or to comply with changes in regulatory requirements. If the updates involve material changes to the collection, protection, use or disclosure of Personal Information, Pearson will provide notice of the change through a conspicuous notice on this site or other appropriate way. Continued use of the site after the effective date of a posted revision evidences acceptance. Please contact us if you have questions or concerns about the Privacy Notice or any objection to any revisions.

Last Update: November 17, 2020