1.1 Introduction

1.1 Introduction

Since its debut in 2004, Ruby on Rails has rapidly become one of the most powerful and popular frameworks for building dynamic web applications. Everyone from scrappy startups to huge companies have used Rails: 37signalsGitHubShopifyScribdTwitterDisney,Hulu, the Yellow Pages—the list of sites using Rails goes on and on. There are also many web development shops that specialize in Rails, such as ENTPthoughtbotPivotal Labs, andHashrocket, plus innumerable independent consultants, trainers, and contractors.

What makes Rails so great? First of all, Ruby on Rails is 100% open-source, available under the permissive MIT License, and as a result it also costs nothing to download or use. Rails also owes much of its success to its elegant and compact design; by exploiting the malleability of the underlying Ruby language, Rails effectively creates a domain-specific language for writing web applications. As a result, many common web programming tasks—such as generating HTML, making data models, and routing URLs—are easy with Rails, and the resulting application code is concise and readable.

Rails also adapts rapidly to new developments in web technology and framework design. For example, Rails was one of the first frameworks to fully digest and implement the REST architectural style for structuring web applications (which we’ll be learning about throughout this tutorial). And when other frameworks develop successful new techniques, Rails creatorDavid Heinemeier Hansson and the Rails core team don’t hesitate to incorporate their ideas.Perhaps the most dramatic example is the merger of Rails and Merb, a rival Ruby web framework, so that Rails now benefits from Merb’s modular design, stable API, and improved performance.

Finally, Rails benefits from an unusually enthusiastic and diverse community. The results include hundreds of open-source contributors, well-attended conferences, a huge number ofgems (self-contained solutions to specific problems such as pagination and image upload), a rich variety of informative blogs, and a cornucopia of discussion forums and IRC channels.The large number of Rails programmers also makes it easier to handle the inevitable application errors: the “Google the error message” algorithm nearly always produces a relevant blog post or discussion-forum thread.

1.1.1 Comments for various readers

The Rails Tutorial contains integrated tutorials not only for Rails, but also for the underlying Ruby language, the RSpec testing framework, HTMLCSS, a small amount of JavaScript, and even a little SQL. This means that, no matter where you currently are in your knowledge of web development, by the time you finish this tutorial you will be ready for more advanced Rails resources, as well as for the more systematic treatments of the other subjects mentioned. It also means that there’s a lot of material to cover; if you don’t already have much experience programming computers, you might find it overwhelming. The comments below contain some suggestions for approaching the Rails Tutorial depending on your background.

All readers: One common question when learning Rails is whether to learn Ruby first. The answer depends on your personal learning style and how much programming experience you already have. If you prefer to learn everything systematically from the ground up, or if you have never programmed before, then learning Ruby first might work well for you, and in this case I recommend Beginning Ruby by Peter Cooper. On the other hand, many beginning Rails developers are excited about making web applications, and would rather not slog through a 500-page book on pure Ruby before ever writing a single web page. In this case, I recommend following the short interactive tutorial at Try Ruby,2 and then optionally do the free tutorial at Rails for Zombies3 to get a taste of what Rails can do.

Another common question is whether to use tests from the start. As noted in the introduction, the Rails Tutorial uses test-driven development (also called test-first development), which in my view is the best way to develop Rails applications, but it does introduce a substantial amount of overhead and complexity. If you find yourself getting bogged down by the tests, I suggest either skipping them on a first reading or (even better) using them as a tool to verify your code’s correctness without worrying about how they work.This latter strategy involves creating the necessary test files (called specs) and filling them with the test code exactly as it appears in the book. You can then run the test suite (as described in Chapter 5) to watch it fail, then write the application code as described in the tutorial, and finally re-run the test suite to watch it pass.

Inexperienced programmers: The Rails Tutorial is not aimed principally at beginning programmers, and web applications, even relatively simple ones, are by their nature fairly complex. If you are completely new to web programming and find the Rails Tutorial too difficult, I suggest learning the basics of HTML and CSS and then giving the Rails Tutorialanother go. (Unfortunately, I don’t have a personal recommendation here, but Head First HTML looks promising, and one reader recommends CSS: The Missing Manual by David Sawyer McFarland.) You might also consider reading the first few chapters of Beginning Ruby by Peter Cooper, which starts with sample applications much smaller than a full-blown web app. That said, a surprising number of beginners have used this tutorial to learn web development, so I suggest giving it a try, and I especially recommend the Rails Tutorialscreencast series4 to give you an “over-the-shoulder” look at Rails software development.

Experienced programmers new to web development: Your previous experience means you probably already understand ideas like classes, methods, data structures, etc., which is a big advantage. Be warned that if your background is in C/C++ or Java, you may find Ruby a bit of an odd duck, and it might take time to get used to it; just stick with it and eventually you’ll be fine. (Ruby even lets you put semicolons at the ends of lines if you miss them too much.) The Rails Tutorial covers all the web-specific ideas you’ll need, so don’t worry if you don’t currently know a POST from a PATCH.

Experienced web developers new to Rails: You have a great head start, especially if you have used a dynamic language such as PHP or (even better) Python. The basics of what we cover will likely be familiar, but test-driven development may be new to you, as may be the structured REST style favored by Rails. Ruby has its own idiosyncrasies, so those will likely be new, too.

Experienced Ruby programmers: The set of Ruby programmers who don’t know Rails is a small one nowadays, but if you are a member of this elite group you can fly through this book and then move on to developing applications of your own.

Inexperienced Rails programmers: You’ve perhaps read some other tutorials and made a few small Rails apps yourself. Based on reader feedback, I’m confident that you can still get a lot out of this book. Among other things, the techniques here may be more up-to-date than the ones you picked up when you originally learned Rails.

Experienced Rails programmers: This book is unnecessary for you, but many experienced Rails developers have expressed surprise at how much they learned from this book, and you might enjoy seeing Rails from a different perspective.

After finishing the Ruby on Rails Tutorial, I recommend that experienced programmers readThe Well-Grounded Rubyist by David A. Black, Eloquent Ruby by Russ Olsen, or The Ruby Way by Hal Fulton, which is also fairly advanced but takes a more topical approach.

At the end of this process, no matter where you started, you should be ready for the many more intermediate-to-advanced Rails resources out there. Here are some I particularly recommend:

- RailsCasts by Ryan Bates: Excellent (mostly) free Rails screencasts

- Tealeaf Academy: a good online Rails development bootcamp (includes advanced material)

- Code School: Interactive programming courses

- Rails Guides: Good topical and up-to-date Rails references

1.1.2 “Scaling” Rails

Before moving on with the rest of the introduction, I’d like to take a moment to address the one issue that dogged the Rails framework the most in its early days: the supposed inability of Rails to “scale”—i.e., to handle large amounts of traffic. Part of this issue relied on a misconception; you scale a site, not a framework, and Rails, as awesome as it is, is only a framework. So the real question should have been, “Can a site built with Rails scale?” In any case, the question has now been definitively answered in the affirmative: some of the most heavily trafficked sites in the world use Rails. Actually doing the scaling is beyond the scope of just Rails, but rest assured that if your application ever needs to handle the load of Hulu or the Yellow Pages, Rails won’t stop you from taking over the world.

1.1.3 Conventions in this book

The conventions in this book are mostly self-explanatory. In this section, I’ll mention some that may not be.

Both the HTML and PDF editions of this book are full of links, both to internal sections (such as Section 1.2) and to external sites (such as the main Ruby on Rails download page).5

Many examples in this book use command-line commands. For simplicity, all command line examples use a Unix-style command line prompt (a dollar sign), as follows:

$ echo "hello, world" hello, world

Windows users should understand that their systems will use the analogous angle prompt >:

C:\Sites> echo "hello, world" hello, world

On Unix systems, some commands should be executed with sudo, which stands for “substitute user do”.6 By default, a command executed with sudo is run as an administrative user, which has access to files and directories that normal users can’t touch, such as in this example from Section 1.2.2:

$ sudo ruby setup.rb

Most Unix/Linux/OS X systems require sudo by default, unless you are using Ruby Version Manager as suggested in Section; in this case, you would type this instead:

$ ruby setup.rb

Rails comes with lots of commands that can be run at the command line. For example, inSection 1.2.5 we’ll run a local development web server as follows:

$ rails server

As with the command-line prompt, the Rails Tutorial uses the Unix convention for directory separators (i.e., a forward slash /). My Rails Tutorial sample application, for instance, lives in


On Windows, the analogous directory would be


The root directory for any given app is known as the Rails root, but this terminology is confusing and many people mistakenly believe that the “Rails root” is the root directory for Rails itself. For clarity, the Rails Tutorial will refer to the Rails root as the application root, and henceforth all directories will be relative to this directory. For example, the configdirectory of my sample application is


The application root directory here is everything before config, i.e.,


For brevity, when referring to the file


I’ll omit the application root and simply write config/routes.rb.

The Rails Tutorial often shows output from various programs (shell commands, version control status, Ruby programs, etc.). Because of the innumerable small differences between different computer systems, the output you see may not always agree exactly with what is shown in the text, but this is not cause for concern.

Some commands may produce errors depending on your system; rather than attempt theSisyphean task of documenting all such errors in this tutorial, I will delegate to the “Google the error message” algorithm, which among other things is good practice for real-life software development. If you run into any problems while following the tutorial, I suggest consulting the resources listed on the Rails Tutorial help page.7

1.2 Up and running

I think of Chapter 1 as the “weeding out phase” in law school—if you can get your dev environment set up, the rest is easy to get through.—Bob Cavezza, Rails Tutorial readerIt’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 types: text editor/command line environments, and integrated development environments (IDEs).Let’s consider the latter first.


The most prominent Rails IDEs are RadRails and RubyMine. I’ve heard especially good things about RubyMine, and one reader (David Loeffler) has assembled notes on how to use RubyMine with this tutorial.8 If you’re comfortable using an IDE, I suggest taking a look at the options mentioned to see what fits with the way you work.

Text editors and command lines

Instead of using an IDE, I prefer to 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.

- Text editor: I recommend Sublime Text 2, an outstanding cross-platform text editor that is simultaneously easy to learn and industrial-strength.9 Sublime Text is heavily influenced by TextMate, and in fact is compatible with most TextMate customizations, such as snippets and color schemes. (TextMate, which is available only on OS X, is still a good choice if you use a Mac.) A second excellent choice is Vim,10 versions of which are available for all major platforms. Sublime Text can be obtained commercially, whereas Vim can be obtained at no cost; both are industrial-strength editors, but in my experience Sublime Text is much more accessible to beginners.

- Terminal: On OS X, I recommend either use iTerm or the native Terminal app. On Linux, the default terminal is fine. On Windows, many users prefer to develop Rails applications in a virtual machine running Linux, in which case your command-line options reduce to the previous case. If developing within Windows itself, I recommend using the command prompt that comes with Rails Installer (Section

If you decide to use Sublime Text, you might want to follow the optional setup instructions for Rails Tutorial Sublime Text.11 (Such configuration settings can be fiddly and error-prone, so I mainly recommend them for more advanced users; Sublime Text is an excellent choice for editing Rails applications even without the advanced setup.)

Image of 2353 article

Figure 1.1: A text editor/command line development environment. (full size)


Although there are many web browsers to choose from, the vast majority of Rails programmers use Firefox, Safari, or Chrome when developing. All three browsers include a built-in “Inspect element” feature available by right- (or control-)clicking on any part of the page.

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 Sublime Text 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, as with an apprentice carpenter striving to master the chisel or the plane, there is no subsitute for mastering the tools of your trade, and in the end the reward is worth the effort.

1.2.2 Ruby, RubyGems, Rails, and Git

Practically all the software in the world is either broken or very difficult to use. So users dread software. They’ve been trained that whenever they try to install something, or even fill out a form online, it’s not going to work. I dread installing stuff, and I have a Ph.D. in computer science.—Paul Graham, in Founders at Work by Jessica LivingstonNow it’s time to install Ruby and Rails. I’ve done my best to cover as many bases as possible, but systems vary, and many things can go wrong during these steps. Be sure to Google the error message or consult the Rails Tutorial help page if you run into trouble. Also, there’s a new resource called Install Rails from One Month Rails that might help you if you get stuck.

Unless otherwise noted, you should use the exact versions of all software used in the tutorial, including Rails itself, if you want the same results. Sometimes minor version differences will yield identical results, but you shouldn’t count on this,especially with respect to Rails versions. The main exception is Ruby itself: 1.9.3 and 2.0.0 are virtually identical for the purposes of this tutorial, so feel free to use either one.

Rails Installer (Windows)

Installing Rails on Windows used to be a real pain, but thanks to the efforts of the good people at Engine Yard—especially Dr. Nic Williams and Wayne E. Seguin—installing Rails and related software on Windows is now easy. If you are using Windows, go to Rails Installerand download the Rails Installer executable and view the excellent installation video.Double-click the executable and follow the instructions to install Git (so you can skipSection, Ruby (skip Section, RubyGems (skip Section, and Rails itself (skip Section Once the installation has finished, you can skip right to the creation of the first application in Section 1.2.3.

Bear in mind that the Rails Installer might use a slightly different version of Rails from the one installed in Section, which might cause incompatibilities. To fix this, I am currently working with Nic and Wayne to create a list of Rails Installers ordered by Rails version number.

Install Git

Much of the Rails ecosystem depends in one way or another on a version control systemcalled 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. (This can be painful and error-prone, and I actually dread having to install new versions of Ruby, but unfortunately it’s the cost of doing business.)

It’s possible that your system already has Ruby installed. Try running

$ ruby -v

to see the version number. Rails 4 requires Ruby 1.9 or later and on most systems works best with Ruby 2.0. (In particular, it won’t work Ruby 1.8.7.) This tutorial assumes that most readers are using Ruby 1.9.3 or 2.0.0, but Ruby 1.9.2 should work as well. Note: I’ve had reports from Windows users that Ruby 2.0 is sketchy, so I recommend using Ruby 1.9.3 if you’re on Windows.

As part of installing Ruby, if you are using OS X or Linux I strongly recommend using Ruby Version Manager (RVM) or rbenv, which allow 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 different versions of Ruby or Rails on the same machine. Unfortunately, RVM and rbenv can’t be used on the same system simultaneously, and since I’ve been using RVM longer that’s the one I use in this tutorial. I hear great things about rbenv, though, so you should feel free to use that if you already know it or if you have access to a local rbenv expert.

As a prerequisite, OS X users may need to install the Xcode developer tools. To avoid the (huge) full installation, I recommend the much smaller Command Line Tools for Xcode.12

To get started with the Ruby installation, first install RVM:

$ curl -sSL https://get.rvm.io | bash -s stable

(If you have RVM installed, you should run

$ rvm get stable

to ensure that you have the latest version.)

You can then get Ruby set up by examining the requirements for installing it:

$ rvm requirements

If you get the message “command not found”, you should run source on the rvm executable:

$ source ~/.rvm/scripts/rvm

On my system, I had to install the following (using Homebrew, a package management system for OS X):

$ brew install libtool libxslt libksba openssl

On Linux, you can accomplish similar things with apt-get or yum.

I also had to install a YAML library:

# For Mac with Homebrew $ brew install libyaml # For Debian-based Linux systems $ apt-get install libyaml-dev # For Fedora/CentOS/RHEL Linux systems $ yum install libyaml-devel

Finally, I needed to tell RVM where OpenSSL was located when installing Ruby 2.0.0:

$ rvm install 2.0.0 --with-openssl-dir=$HOME/.rvm/usr

On some systems, especially on Macs using Homebrew, the location of OpenSSL may be different, and you might have to run this command instead:

$ rvm install 2.0.0 --with-openssl-dir=$HOME/.rvm/opt/openssl

Unfortunately, lots of things can go wrong along the way. I’ve done my best to cover some of the most common cases, but the only general solution is web searches and determination.

After installing Ruby, you should configure your system for the other software needed to run Rails applications. This typically involves installing 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. For the purposes of this tutorial, I suggest creating a gemset called railstutorial_rails_4_0:

$ rvm use 2.0.0@railstutorial_rails_4_0 --create --default Using /Users/mhartl/.rvm/gems/ruby-2.0.0-p0 with gemset railstutorial_rails_4_0

This command creates (--create) the gemset railstutorial_rails_4_0 associated with Ruby 2.0.0 while arranging to start using it immediately (use) and setting it as the default (--default) gemset, so that any time we open a new terminal window the2.0.0@railstutorial_rails_4_0 Ruby/gemset combination is automatically selected.RVM supports a large variety of commands for manipulating gemsets; see the documentation at http://rvm.beginrescueend.com/gemsets/. If you ever get stuck with RVM, running commands like these should help you get your bearings:

$ rvm help $ rvm gemset help

For more information on RVM, I also recommend taking a look at the article Ruby Version Manager (RVM) Overview for Rails Newbs.13

Install RubyGems

RubyGems is a package manager for Ruby projects, and there are many useful 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 /Users/mhartl/.rvm/rubies/ruby-2.0.0-p0/bin/gem

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

$ ruby setup.rb

(If you get a permissions error here, recall from Section 1.1.3 that you may have to use sudo.)

If you already have RubyGems installed, you should make sure your system uses the version used in this tutorial:

$ gem update --system 2.1.9

Freezing your system to this particular version will help prevent conflicts as RubyGems changes in the future.

When installing gems, by default RubyGems generates two different kinds of documentation (called ri and rdoc), but many Ruby and Rails developers find that the time to build them isn’t worth the benefit. (Many programmers rely on online documentation instead of the native ri and rdoc documents.) To prevent the automatic generation of the documentation, I recommend making a gem configuration file called .gemrc in your home directory as inListing 1.1 with the line in Listing 1.2. (The tilde “~” means “home directory”, while the dot .in .gemrc makes the file hidden, which is a common convention for configuration files. )

Listing 1.1: Creating a gem configuration file.

$ subl ~/.gemrc

Here subl is the command-line command to launch Sublime Text on OS X, which you can set up using the Sublime Text 2 documentation for the OS X command line. If you’re on a different platform, or if you’re using a different editor, you should replace this command as necessary (i.e., by double-clicking the application icon or by using an alternate command such as mate, vim, gvim, or mvim). For brevity, throughout the rest of this tutorial I’ll usesubl as a shorthand for “open with your favorite text editor.”

Listing 1.2: Suppressing the ri and rdoc documentation in .gemrc.

install: --no-rdoc --no-ri update: --no-rdoc --no-ri

Install Rails

Once you’ve installed RubyGems, installing Rails should be easy. This tutorial standardizes on Rails 4.0, which we can install as follows:

$ gem install rails --version 4.0.5

To check your Rails installation, run the following command to print out the version number:

$ rails -v Rails 4.0.5

Important note: Be sure not to install Rails 4.1, which is not compatible with this tutorial.(The upcoming 3rd edition will use Rails 4.1 or later.)

Note: If you installed Rails using the Rails Installer in Section, there might be slight version differences. As of this writing, those differences are not relevant, but in the future, as the current Rails version diverges from the one used in this tutorial, these differences may become significant.

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

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


$ sudo yum install libxslt-devel libxml2-devel libsqlite3-devel

1.2.3 The first application

Virtually all Rails applications start the same way, by running rails new command. This handy command creates a skeleton Rails application in a directory of your choice. To get started, make a directory for your Rails projects and then run rails new to make the first application (Listing 1.3):

Listing 1.3: Running rails new to generate a new application.

$ mkdir rails_projects $ cd rails_projects $ rails new first_app create create README.rdoc create Rakefile create config.ru create .gitignore create Gemfile create app create app/assets/javascripts/application.js create app/assets/stylesheets/application.css create app/controllers/application_controller.rb . . . create test/test_helper.rb create tmp/cache create tmp/cache/assets create vendor/assets/javascripts create vendor/assets/javascripts/.keep create vendor/assets/stylesheets create vendor/assets/stylesheets/.keep run bundle install . . . Your bundle is complete! Use `bundle show [gemname]` to see where a bundled gem is installed.

As seen at the end of Listing 1.3, running rails new automatically runs the bundle install command after the file creation is done. If that step doesn’t work right now, don’t worry; follow the steps in Section 1.2.4 and you should be able to get it to work.

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. In particular, starting inSection 5.2.1 we’ll discuss the app/assets directory, part of the asset pipeline that makes it easier than ever to organize and deploy assets such as cascading style sheets and JavaScript files.

Image of 2353 article

Figure 1.2: The directory structure for a newly created Rails app.


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

app/assetsApplications assets such as cascading style sheets (CSS), JavaScript files, and images

bin/Binary executable files

config/Application configuration

db/Database files

doc/Documentation for the application

lib/Library modules

lib/assetsLibrary assets such as cascading style sheets (CSS), JavaScript files, and images

log/Application log files

public/Data accessible to the public (e.g., web browsers), such as error pages

bin/railsA program for generating code, opening console sessions, or starting a local server

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

tmp/Temporary files

vendor/Third-party code such as plugins and gems

vendor/assetsThird-party assets such as cascading style sheets (CSS), JavaScript files, and images

README.rdocA brief description of the application

RakefileUtility tasks available via the rake command

GemfileGem requirements for this app

Gemfile.lockA list of gems used to ensure that all copies of the app use the same gem versions

config.ruA configuration file for Rack middleware

.gitignorePatterns for files that should be ignored by Git

Table 1.1: A summary of the default Rails directory structure.

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. As noted briefly in Section 1.2.3, Bundler is run automatically (via bundle install) by the rails command, but in this section we’ll make some changes to the default application gems and run Bundler again. This involves opening the Gemfilewith your favorite text editor:

$ cd first_app/ $ subl Gemfile

The result should look something like Listing 1.4. The code in this file is Ruby, but don’t worry at this point about the syntax; Chapter 4 will cover Ruby in more depth.

Listing 1.4: The default Gemfile in the first_app directory.

source 'https://rubygems.org' # Use sqlite3 as the database for Active Record gem 'sqlite3' # Use SCSS for stylesheets gem 'sass-rails', '~> 4.0.1' # Use Uglifier as compressor for JavaScript assets gem 'uglifier', '>= 1.3.0' # Use CoffeeScript for .js.coffee assets and views gem 'coffee-rails', '~> 4.0.0' # See https://github.com/sstephenson/execjs#readme for more supported runtimes # gem 'therubyracer', platforms: :ruby # Use jquery as the JavaScript library gem 'jquery-rails' # Turbolinks makes following links in your web application faster. # Read more: https://github.com/rails/turbolinks gem 'turbolinks' # Build JSON APIs with ease. Read more: https://github.com/rails/jbuilder gem 'jbuilder', '~> 1.0.1' group :doc do # bundle exec rake doc:rails generates the API under doc/api. gem 'sdoc', require: false end # Use ActiveModel has_secure_password # gem 'bcrypt-ruby', '~> 3.1.2' # Use unicorn as the app server # gem 'unicorn' # Use Capistrano for deployment # gem 'capistrano', group: :development # Use debugger # gem 'debugger', group: [:development, :test]

Many 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.

Unless you specify a version number to the gem command, Bundler will automatically install the latest version of the gem. Unfortunately, gem updates often cause minor but potentially confusing breakage, so in this tutorial we’ll include explicit version numbers known to work, as seen in Listing 1.5 (which also omits the commented-out lines from Listing 1.4).

Listing 1.5: A Gemfile with an explicit version for each Ruby gem.

source 'https://rubygems.org' ruby '2.0.0' #ruby-gemset=railstutorial_rails_4_0 gem 'rails', '4.0.5' group :development do gem 'sqlite3', '1.3.8' end gem 'sass-rails', '4.0.1' gem 'uglifier', '2.1.1' gem 'coffee-rails', '4.0.1' gem 'jquery-rails', '3.0.4' gem 'turbolinks', '1.1.1' gem 'jbuilder', '1.0.2' group :doc do gem 'sdoc', '0.3.20', require: false end

Listing 1.5 adds the lines

ruby '2.0.0' #ruby-gemset=railstutorial_rails_4_0

identifying the version of Ruby expected by the application (especially useful when deploying applications (Section 1.4)), along with the RVM gemset (Section Because the gemset line starts with #, which is the Ruby comment character, it will be ignored if you aren’t using RVM, but if you are RVM will conveniently use the right Ruby version/gemset combination upon entering the application directory. (If you are using a version of Ruby other than 2.0.0, you should change the Ruby version line accordingly.)

The updated Gemfile also changes the line for jQuery, the default JavaScript library used by Rails, from

gem 'jquery-rails'


gem 'jquery-rails', '3.0.4'

We’ve also changed

gem 'sqlite3'


group :development do gem 'sqlite3', '1.3.8' end

which forces Bundler to install version 1.3.8 of the sqlite3 gem. Note that we’ve also taken this opportunity to arrange for the gem to be included only in a development environment (Section 7.1.1), which prevents potential conflicts with the database used by Heroku (Section 1.4).

Listing 1.5 also changes a few other lines, converting

# Use SCSS for stylesheets gem 'sass-rails', '~> 4.0.0' # Use Uglifier as compressor for JavaScript assets gem 'uglifier', '>= 1.3.0' # Use CoffeeScript for .js.coffee assets and views gem 'coffee-rails', '~> 4.0.0'


gem 'sass-rails', '4.0.1' gem 'uglifier', '2.1.1' gem 'coffee-rails', '4.0.1'

The syntax

gem 'uglifier', '>= 1.3.0'

installs the latest version of the uglifier gem (which handles file compression for the asset pipeline) as long as it’s greater than or equal to version 1.3.0—even if it’s, say, version 7.2.Meanwhile, the code

gem 'coffee-rails', '~> 4.0.0'

installs the gem coffee-rails (also needed by the asset pipeline) as long as it’s newer than version 4.0.0 but not newer than 4.1. In other words, the >= notation always installs the latest gem when you run bundle install, whereas the ~> 4.0.0 notation only installs updated gems representing minor point releases (e.g., from 4.0.0 to 4.0.1), but not major point releases (e.g., from 4.0 to 4.1). Unfortunately, experience shows that even minor point releases can break things, so for the Rails Tutorial we’ll err on the side of caution by including exact version numbers for virtually all gems. You are welcome to use the most up-to-date version of any gem, including using the ~> construction in the Gemfile (which I generally recommend for more advanced users), but be warned that this may cause the tutorial to act unpredictably.

Once you’ve assembled the proper Gemfile, install the gems using bundle update14 andbundle install:

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

The bundle install command 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, visible only from your development machine:

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

(If your system complains about the lack of a JavaScript runtime, visit the execjs page at GitHub for a list of possibilities. I particularly recommend installing Node.js.) This tells us that the application is running on port number 300015 at the address This address tells the computer to listen on every available IP address configured on that specific machine; in particular, we can view the application using the special address, which is also known as localhost. We can see the result of visiting http://localhost:3000/ in Figure 1.3.

Image of 2353 article

Figure 1.3: The default Rails page.

To see information about our first application, click on the link “About your application’s environment”. The result is shown in Figure 1.4. (Figure 1.4 represents the environment on my machine when I made the screenshot; your results may differ.)

Image of 2353 article

Figure 1.4: The default page 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) inSection 5.3.2.