Buy this Book
Print Book $39.99 PDF $27.99 Read it Now!
Print Book £28.50
Add to UK Cart
Reprint Licensing

Rails Cookbook
Rails Cookbook

By Rob Orsini
Book Price: $39.99 USD
£28.50 GBP
PDF Price: $27.99

Cover | Table of Contents


Table of Contents

Chapter 1: Getting Started
Since it first appeared in July 2004, Ruby on Rails has revolutionized the process of developing web applications. It has enabled web developers to become much faster and more efficient, allowing for quicker application development—a critical advantage in these days of “web time.” How does Rails do it? There are a few reasons behind Rails’ success:
Convention over configuration
Rather than forcing you to configure every aspect of your application, Rails is full of conventions. If you can follow those conventions, you can do away with almost all configuration files and a lot of extra coding. If you can’t follow those conventions, you’re usually no worse off than you were in your previous environment.
Liberal use of code generation
Rails can write a lot of your code for you. For example, when you need a class to represent a table in your database, you don’t have to write most of the methods: Rails looks at the table’s definition and creates most of the class for you on the fly. You can mix in many extensions to add special behavior, and when you really need to, you can add your own methods. You’ll find that you’re writing only a fraction as much code as you did with other web frameworks.
Don’t repeat yourself (DRY)
DRY is a slogan you’ll hear frequently. With Rails, you need to code behavior only once; you never (well, almost never) have to write similar code in two different places. Why is this important? Not because you type less, but because you’re less likely to make mistakes by modifying one chunk of code, and not another.
David Heinemeier Hansson and the other Ruby on Rails core developers have learned from the mistakes of other web application frameworks and taken a huge step forward. Rather than provide an extremely complex platform that can solve every problem out of the box if you can only understand it, Rails solves a very simple problem extremely well. With that solution under your belt, you’ll find that it’s a lot easier to work up to the hard problems. It’s often easier, in fact, to solve the hard problem for yourself with Rails than to understand some other platform’s solution. Want to find out whether Rails is everything it’s cracked up to be? Don’t wait; try it. If you’re not a Ruby developer yet, don’t worry; you only need to know a limited amount of Ruby to use Rails. I’d be willing to bet that you’ll want to learn more, though.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introduction
Since it first appeared in July 2004, Ruby on Rails has revolutionized the process of developing web applications. It has enabled web developers to become much faster and more efficient, allowing for quicker application development—a critical advantage in these days of “web time.” How does Rails do it? There are a few reasons behind Rails’ success:
Convention over configuration
Rather than forcing you to configure every aspect of your application, Rails is full of conventions. If you can follow those conventions, you can do away with almost all configuration files and a lot of extra coding. If you can’t follow those conventions, you’re usually no worse off than you were in your previous environment.
Liberal use of code generation
Rails can write a lot of your code for you. For example, when you need a class to represent a table in your database, you don’t have to write most of the methods: Rails looks at the table’s definition and creates most of the class for you on the fly. You can mix in many extensions to add special behavior, and when you really need to, you can add your own methods. You’ll find that you’re writing only a fraction as much code as you did with other web frameworks.
Don’t repeat yourself (DRY)
DRY is a slogan you’ll hear frequently. With Rails, you need to code behavior only once; you never (well, almost never) have to write similar code in two different places. Why is this important? Not because you type less, but because you’re less likely to make mistakes by modifying one chunk of code, and not another.
David Heinemeier Hansson and the other Ruby on Rails core developers have learned from the mistakes of other web application frameworks and taken a huge step forward. Rather than provide an extremely complex platform that can solve every problem out of the box if you can only understand it, Rails solves a very simple problem extremely well. With that solution under your belt, you’ll find that it’s a lot easier to work up to the hard problems. It’s often easier, in fact, to solve the hard problem for yourself with Rails than to understand some other platform’s solution. Want to find out whether Rails is everything it’s cracked up to be? Don’t wait; try it. If you’re not a Ruby developer yet, don’t worry; you only need to know a limited amount of Ruby to use Rails. I’d be willing to bet that you’ll want to learn more, though.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Joining the Rails Community
You know that Rails is an evolving open source project, and you want to stay on top of the latest developments. Where do you get your questions answered, and how do you know what new features are being developed?
Like most popular open source projects, Rails has a number of mailing lists that developers, system administrators, and other interested parties can join to stay abreast of the latest developments. These lists also have searchable archives that will help you understand the evolution of a feature. Currently, the following mailing lists are :
rubyonrails-talk
rubyonrails-core
Discussions about the core development and future of Rails: http://groups.google.com/group/rubyonrails-core
rubyonrails-security
rubyonrails-spinoffs
Discussions about prototype and script.aculo.us: http://groups.google.com/group/rubyonrails-spinoffs
Also, http://ruby-forum.com has a number of Rails- and Ruby-related lists that you can join or read on the Web.
Another venue for communicating about Rails is the #rubyonrails IRC channel on the Freenode IRC network (http://irc.freenode.net). If you’re new to IRC, you can learn more at http://www.irchelp.org. You’ll need an IRC client such as X-Chat (http://www.xchat.org), Colloquy (http://colloquy.info), or for terminal fans, Irssi (http://www.irssi.org).
One great place to ask questions and look for answers is Rails Weenie (http://rails.techno-weenie.net). This site uses a points-based system in an attempt to persuade people to answer more questions, and to ask more sensible questions. When you create an account, you automatically receive five points. You can offer these points as a reward for questions you want answered. If someone answers the question, they get the number of points you offered. Also, if you answer other people’s questions, you get the number of points they offered. It’s not as responsive as IRC, but you’re far more likely to get a more thorough answer to your question.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Finding Documentation
You’re beginning to develope Rails applications, and you have questions. You need to find the latest documentation for Ruby, Rails, and RubyGems libraries.
The documentation for the latest stable version of the Rails API is online at http://api.rubyonrails.com. A group of hardcore Rails developers also maintains documentation on the bleeding-edge version of Rails at http://caboo.se/doc. The latest Ruby documentation is always available at http://www.ruby-doc.org. Here you can find documentation on the Ruby Core library, the Ruby Standard Library, and the C API. In regards to third-party libraries, a comprehensive set of RubyGems documentation is available at http://www.gemjack.com. You can also view documentation on any RubyGems you have installed on your local system by starting the gem server with the following command:
$ gem_server
            
When the gem server is running, you can view the documentation for your local gem repository at http://localhost:8808. Additional Rails documentation can be found on the wiki at http://wiki.rubyonrails.org/rails. There you’ll find a vast amount of user contributed content. While there’s valuable information on the wiki, be warned that some of it can be out of date or inaccurate.
Of late, there’s been a growing trend to consolidate essential documentation into so-called cheatsheets. A quick web search for Ruby, Rails, or Prototype cheatsheets should yield some valuable results. One that stands out is the cheat RubyGem—it installs a command-line tool to produce Ruby-centric cheatsheets right from your terminal. For more information, visit http://cheat.errtheblog.com or install the library with:
$ sudo gem install cheat --source require.errtheblog.com  
            
Last but not least, GotApi (http://www.gotapi.com) might best be described as a documentation aggregator. It’s a very useful site for looking up not only Ruby and Rails documentation, but other related docs (like JavaScript and CSS).
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Installing MySQL
You want to install a MySQL relational database server to be used by your Rails .

Windows

If you’re a Windows user, download and unzip mysql-5.0.18-win32.zip from http://dev.mysql.com/downloads. Depending on which version of MySQL you download, you should see either a setup.exe file or a .msi file. Click on one of these to start the installation wizard. For most cases, you can select the standard configuration, which includes the mysql command-line client and several other administration utilities, such as mysqldump.
By default, the installation wizard sets up MySQL as a service that starts automatically. Another option is to have the installer include MySQL’s binary directory in the Windows PATH, allowing you to call the MySQL utilities from the Windows command line. Once the installation is complete, you can start up mysql as the root user at the command prompt as shown in .
Figure : Interaction with MySQL from the command prompt
You can stop and start MySQL from the Windows command prompt using the net command:
C:\> net start mysql
               
C:\> net stop mysql
               
Lastly, install the MySQL gem for maximum performance:
C:\> gem install mysql
               
The gem installer will present you with a list of versions and prompt you for the one you wish to install. Be sure to choose the highest version of the gem that ends with (mswin32).

Linux

To install MySQL on a Debian GNU/Linux system, start by making sure your sources.list file contains the appropriate archive locations:
$ cat /etc/apt/sources.list
deb http://archive.progeny.com/debian/ etch main
deb-src http://archive.progeny.com/debian/ etch main

deb http://security.debian.org/ etch/updates main
deb-src http://security.debian.org/ etch/updates main
Then run apt-get update to resynchronize the package index files from the repository sources:
$ sudo apt-get update
               
To install MySQL 5.0, install the
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Installing PostgreSQL
You want to install a PostgreSQL database server to be accessed by your Rails applications.

Windows

If you’re a Windows user, download the latest version from http://www.postgresql.org/download, and unpack the ZIP archive. Inside, you’ll find a directory containing the PostgreSQL Windows installer (the filename extension is .msi). Launch the installation wizard by double-clicking on this file.
The installation options allow you to include several database tools and interfaces. Make sure that the psql tool (the command-line user interface) is included; if you prefer a GUI administration tool, also include pgAdmin III.

Linux

To install PostgreSQL on a Debian GNU/Linux system, point your sources.list file to the Debian archive locations you’d like to use. Then run apt-get update to resynchronize the package index files from the repository sources.
$ cat /etc/apt/sources.list
deb http://archive.progeny.com/debian/ etch main
deb-src http://archive.progeny.com/debian/ etch main

deb http://security.debian.org/ etch/updates main
deb-src http://security.debian.org/ etch/updates main
$ sudo apt-get update
               
Install the PostgreSQL Debian GNU/Linux package (postgresql-8.1 as of this writing) and development package. These packages include dependent packages for the PostgreSQL client and common libraries as well as header files necessary for compilation of the Ruby PostgreSQL driver.
$ sudo apt-get install postgresql-8.1 postgresql-dev
               
Now, su to the postgres user, and connect to the server with the client program psql:
$ sudo su postgres
$ psql
Welcome to psql 8.1.0, the PostgreSQL interactive terminal.

Type:  \copyright for distribution terms
       \h for help with SQL commands
       \? for help with psql commands
       \g or terminate with semicolon to execute query
       \q to quit

postgres=# \l
        List of databases
   Name    |  Owner   | Encoding  
-----------+----------+-----------
 postgres  | postgres | SQL_ASCII
 template0 | postgres | SQL_ASCII
 template1 | postgres | SQL_ASCII
(3 rows)

postgres=# 
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Installing Rails
You want to download and install Ruby on Rails on Linux or Windows.
Before you can install Rails, you must have a working build environment and install Ruby itself. Ruby comes with most recent Linux distributions, but you should check to make sure you have a version that’s compatible with Rails: 1.8.5, 1.8.4, and 1.8.2 work; 1.8.3 does not. Here’s how to check your Ruby version:
$ which ruby
/usr/local/bin/ruby
$ ruby -v
ruby 1.8.4 (2005-10-29) [i486-linux]
If you don’t have Ruby installed, you can either install it using your distribution’s package manager or download and install it from source. For a source install, get the latest stable version of Ruby from http://rubyforge.org/projects/ruby. Unpack the archive into a convenient place, like /usr/local/src.
$ cd /usr/local/src/ruby-1.8.4
./configure
make
sudo make install
To install Ruby on a Debian system, use Advanced Package Tool (APT) to download a precompiled binary package from the Debian package repository. Start by updating APT’s package cache, then install the Ruby 1.8 package. You’ll also need several other packages to get the full functionality of your Ruby development environment (e.g., libreadline is required for Readline support in irb).
$ apt-get update
            
$ sudo apt-get install ruby1.8-dev ruby1.8 ri1.8 rdoc1.8 \
irb1.8 libreadline-ruby1.8 libruby1.8
            
Once you’ve made sure you have a “good” version of Ruby on your system, proceed to install RubyGems. You can get the latest version of RubyGems from the RubyForge project page: http://rubyforge.org/projects/rubygems. Download the source code into /usr/local/src or another convenient location. Move into the source directory, and run the setup.rb script with Ruby. Note that the filenames shown here are current as of this writing, but you should use the latest version.
$ tar xzvf rubygems-0.9.0.tgz
$ cd rubygems-0.9.0
$ sudo ruby setup.rb
            
Once you have RubyGems installed, you can install Rails:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Fixing Ruby and Installing Rails on OS X 10.4 Tiger
Mac OS X 10.4 Tiger ships with a version of Ruby that doesn’t work with the latest versions of Rails. You can fix this by installing the latest stable version of Ruby and its prerequisites. With Ruby up to date, you can then install Rails.
Install the latest stable version of Ruby in /usr/local on your filesystem.
Set your PATH variable to include /usr/local/bin and /usr/local/sbin. Add the following line to your ~/.bash_profile:
~$ export PATH="/usr/local/bin:/usr/local/sbin:$PATH"
            
Make sure to “source” this file to ensure that the value of the PATH variable is available to your current shell.
~$ source .bash_profile
            
Create the directory /usr/local/src, and cd into it. This will be a working directory where you’ll download and configure a number of source files.
Install GNU Readline, which gives you command-line editing features, including history. Readline is needed for the interactive Ruby interpreter, irb, and the Rails console to work correctly.
/usr/local/src$ curl -O ftp://ftp.cwru.edu/pub/bash/readline-5.1.tar.gz
/usr/local/src$ tar xzvf readline-5.1.tar.gz
/usr/local/src$ cd readline-5.1
            
(If you’re running Panther, you’ll need to execute this Perl command; otherwise skip to the next step.)
/usr/local/src/readline-5.1$ perl -i.bak -p -e \ 
            "s/SHLIB_LIBS=.*/SHLIB_LIBS='-lSystem -lncurses -lcc_dynamic'/g" \  
            support/shobj-conf
            
Configure Readline, specifying /usr/local as the installation directory by setting the prefix option of configure:
/usr/local/src/readline-5.1$ ./configure --prefix=/usr/local
/usr/local/src/readline-5.1$ make
/usr/local/src/readline-5.1$ sudo make install
/usr/local/src/readline-5.1$ cd ..
            
Download, and unpack the latest stable version of Ruby. Configure it to install in /usr/local, enable threads, and enable Readline support by specifying the location of the Readline:
/usr/local/src$ curl -O \
                   ftp://ftp.ruby-lang.org/pub/ruby/1.8/ruby-1.8.4.tar.gz
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Running Rails in OS X with Locomotive
You don’t have administrative privileges to install Rails and its dependencies, system-wide. You want to install Rails on Mac OS X in a self-contained and isolated .
Use Locomotive to run a fully functional Rails environment within Mac OS X. Obtain a copy of the latest version of Locomotive from http://locomotive.raaum.org. The latest version as of this writing is Locomotive 2.0.8.
Open and attach the downloaded disk image (we used Locomotive_1.0.0a.dmg for ) by double-clicking on it. In the disk image, you should see a Locomotive directory and another directory containing license information. Copy the Locomotive directory into your Applications folder. It’s important to copy the entire Locomotive directory and not just Locomotive.app because the Bundles directory is required to exist next to the Locomotive application under your Applications directory.
Once installed, launching Locomotive opens up a project control window with a list of the Rails projects you have configured, their port numbers, and their status (running or not). You can add existing Rails projects or create new ones by selecting “Create New...” or “Add Existing...” from the Rails menu. Creating a new project opens up a dialog box prompting you for the name of your Rails application and its location on your filesystem. If you already have a Rails project on your filesystem, you can add it to your Locomotive projects, specifying its server and environment settings.
Locomotive assumes you have a Rails-compatible database installed and that you’ve created three databases based on the name of your Rails application. For example, if your application is named MyBooks, the default configuration expects databases named MyBooks_development, MyBooks_test, and MyBooks_production. The default configuration connects to these databases with the root user and no password.
Click Create to create the structure of your Rails application in the directory you specified. The MyBooks application now appears in the project control window. With that project selected, you can open the project files in your preferred editing environment. View these options by right-clicking to bring up the contextual menu.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Running Rails in Windows with Instant Rails
You develop on a Windows box, and you’d like to install and configure Rails and all its dependencies at one time. You’d also like the entire installation to exist in a self-contained and isolated environment, so that you don’t need administrative privileges to install it, and it won’t conflict with any software already installed on the box.
Download and install Instant Rails to get Rails up and running quickly in a Windows environment. You can get the latest release at the Instant Rails RubyForge page at
Unzip the archive you downloaded, and move the resulting directory to a file path containing no spaces, such as C:\rails\InstantRails. To launch Instant Rails, navigate to that directory, and double-click the InstantRails.exe executable. When it starts, you’ll see the Instant Rails status window. Clicking the I graphic in this window displays a menu that serves as the starting point for most configuration tasks. To create a new Rails application, click on the I and select Rails Application→Open Ruby Console Window. Type the following command to create an application called demo:
C:\InstantRails\rails_apps>rails demo
            
The next step is to create and configure your databases. From the I, select Configure→Database (via phpMyAdmin). This launches phpMyAdmin in your default browser with the URL of http://127.0.0.1/mysql. The default databases for the demo application are demo_development, demo_test and demo_production. You’ll need to create these in phpMyAdmin; you must also create a user named “root” with no .
Now you can start building your Rails application. To create scaffolding for a cds table that you’ve created in your database, open a Rails console window, and navigate to the root of the project. To execute a command in the scripts directory, pass the path to the command as an argument to the Ruby binary:
C:\InstantRails\rails_apps\demo>ruby script\generate scaffold cd
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Updating Rails with RubyGems
You’ve installed Rails using the gem command and probably other Ruby packages as well. You want to manage these packages and upgrade as new versions are released, without worrying about dependencies.
To upgrade Rails and the gems it depends on (e.g., rake, activesupport, activerecord, actionpack, actionmailer, and actionwebservice), type:
$ sudo gem update rails --include-dependencies
            
Once you’ve updated the Rails gems, the only remaining step to upgrading your individual Rails applications (Version 0.14.0 and later) is to get the latest JavaScript libraries. Run the following command from your application’s root directory:
~/project$ rake rails:update:javascripts
            
Test your application to make sure that everything works with the updated libraries.
RubyGems is Ruby’s package manager. It provides a standard way to distribute third-party programs and libraries, called gems. It allows you to install and upgrade gems, while handling dependencies for you. The gem command-line utility lets you install, upgrade, remove, and inspect gems.
Using gem list, you can view which gems you have installed. To get a list of all your installed gems and their versions, use:
$ gem list --local
            
Here’s how to get a listing of all the gems that are available from the remote repository:
$ gem list --remote
            
The syntax for the gem command is gem command [arguments...] [options...]. Many of the commands take either --local or --remote as arguments. To search your local repository as well as the remote repository for gems with “flick” in the name, use :
$ gem search --both flick
            
Here’s how to install a remote gem locally and build its RDoc:
$ sudo gem install --remote rails --rdoc
            
To view detailed information about the contents of a gem, use the specification :
$ gem specification rails
            
You can run gem help or just gem (with no arguments) to get more information on available gem commands and options.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Getting Your Rails Project into Subversion
You want to get your Rails project into a Subversion repository but don’t want your logging and configuration files included.
Create a Subversion repository, and confirm that the repository was created:
/home/svn$ svnadmin create blog
            
/home/svn$ ls blog/
conf  dav  db  format  hooks  locks  README.txt
Change to your Rails project directory:
/home/svn$ cd ~/projects/blog; ls
app  components  config  db  doc  lib  log  public  Rakefile  README  script
test  vendor
Import the entire project. The . in the following command is critical. It specifies to “import everything within this directory”:
~/projects/blog$ svn import -m "initial import" . \
> file:///home/svn/blog
Adding         test
Adding         test/unit
Adding         test/test_helper.rb

...

Adding         public/favicon.ico

Committed revision 1.
~/projects/blog$ 
Now, delete the initial project files:
~/projects$ cd ..; rm -rf blog/
            
If this step scares you, move your files somewhere else until you’re satisfied that you won’t need them any more. But trust me: you won’t. You can now check out your versioned project from its repository:
~/projects$ svn checkout file:///home/svn/blog
A    blog/test
A    blog/test/unitL

...

A    blog/public/favicon.ico
Checked out revision 1.
~/projects$
Now, move back into the project directory, and remove the logfiles from the repository using Subversion; then commit the removal:
~/projects$ cd blog
~/projects/blog$ svn remove log/*
D         log/development.log
D         log/production.log
D         log/server.log
D         log/test.log
~/projects/blog$
~/projects/blog$ svn commit -m 'removed log files'
Deleting       log/development.log
Deleting       log/production.log
Deleting       log/server.log
Deleting       log/test.log

Committed revision 2.
~/projects/blog$ 
Next, instruct Subversion to ignore the logfiles that get recreated by Rails:
~/projects/blog$ svn propset svn:ignore "*.log" log/
property 'svn:ignore' set on 'log'
~/projects/blog$
Now, update the log directory, and commit the property change:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Chapter 2: Rails Development
Rails is geared toward making web development productive and rewarding—so productive, in fact, that it’s been claimed that you can be 10 times more productive in Rails than with other frameworks. You can be your own judge about whether you find Rails more rewarding, but when you’re more productive, you can spend more time solving the problems that are interesting to you, rather than reinventing wheels and building infrastructure. The best way to realize productivity gains is to establish a comfortable development environment. Your primary development tool will be a text editor or integrated development environment (IDE). Getting to know this tool well will allow you to navigate through your application’s source files effectively. You’ll also need tools to interact with Rails at the command line, which means selecting a suitable terminal or console application.
This chapter contains recipes that help you get your Rails development environment dialed in and create the beginnings of a Rails application. I also cover some helpful solutions to common problems associated with Rails development, like generating Ruby documentation (RDoc) for your application or developing against the most current Rails (Edge Rails).
Once you get comfortable creating and working with new Rails projects and have all of your development tools in place, you can really start exploring all that the framework has to offer.
You have Rails installed on your system and want to create your first Rails project.
We’ll assume that you have Ruby, RubyGems, Rails, and one of the databases supported by Rails (MySQL is most popular; PostgreSQL is less popular but also an excellent choice). To create a new Rails application, run the rails command with the path to your new application as an argument. For example, to create your new application at /var/www/cookbook (and the cookbook directory doesn’t exist yet), type the following command in a terminal window:
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Introduction
Rails is geared toward making web development productive and rewarding—so productive, in fact, that it’s been claimed that you can be 10 times more productive in Rails than with other frameworks. You can be your own judge about whether you find Rails more rewarding, but when you’re more productive, you can spend more time solving the problems that are interesting to you, rather than reinventing wheels and building infrastructure. The best way to realize productivity gains is to establish a comfortable development environment. Your primary development tool will be a text editor or integrated development environment (IDE). Getting to know this tool well will allow you to navigate through your application’s source files effectively. You’ll also need tools to interact with Rails at the command line, which means selecting a suitable terminal or console application.
This chapter contains recipes that help you get your Rails development environment dialed in and create the beginnings of a Rails application. I also cover some helpful solutions to common problems associated with Rails development, like generating Ruby documentation (RDoc) for your application or developing against the most current Rails (Edge Rails).
Once you get comfortable creating and working with new Rails projects and have all of your development tools in place, you can really start exploring all that the framework has to offer.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Creating a Rails Project
You have Rails installed on your system and want to create your first Rails project.
We’ll assume that you have Ruby, RubyGems, Rails, and one of the databases supported by Rails (MySQL is most popular; PostgreSQL is less popular but also an excellent choice). To create a new Rails application, run the rails command with the path to your new application as an argument. For example, to create your new application at /var/www/cookbook (and the cookbook directory doesn’t exist yet), type the following command in a terminal window:
$ rails /var/www/cookbook
            
The rails command creates the directory for your project using the path you supplied, as well as a number of subdirectories that organize your project’s code by the function it performs within the MVC environment. The rails command also accepts several command-line options. You can view these options by typing:
$ rails --help
            
The most important of these options is --database=database_type, where database_type is one of the following: mysql, oracle, postgresql, sqlite2, or sqlite3. For example, to use PostgreSQL as your database instead of the default, MySQL, enter the following command:
$ rails /var/www/cookbook --database=postgresql
               
After creating a project with Rails, you should explore the structure of directories it generates, as well as the files that are created. Your new Rails project will include a nice README file that goes over the basics behind Rails, including how to get documentation, debugging Rails, the Rails console, breakpoints, and more.
A new Rails project contains the following directories:
app
Contains all the code that’s specific to this particular application. Most of Rails development happens within the app directory.
app/controllers
Contains controller classes, all of which should inherit ActionController::Base. Each of these files should be named after the model they control followed by
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Jump-Starting Development with Scaffolding
You’ve got a good idea for a new project and have a basic database designed. You want to get a basic Rails application up and running quickly.
Once you have created your database and configured Rails to communicate with it, you can have Rails generate what it calls scaffolding. Scaffolding consists of the basics of a CRUD (create, read, update, and delete) web application, including controller and view code that interact with your model. When you generate scaffolding, you are left with a fully functional, albeit basic, web application that can serve as a starting point for continued development.
There are two ways to generate scaffolding in Rails. The first is to have Rails dynamically generate all the view and controller code needed to get your application running behind the scenes. You do this using the scaffold method of Action Controller. The second is to use the Rails scaffolding generator to create the scaffolding code in your application directory.
To demonstrate how scaffolding works, let’s create a Rails application that lets you store a list of programming languages along with their descriptions. Start by setting up your database. Generate a database migration script with:
$ ruby script/generate migration build_db
            
Doing so creates a file called 001_build_db.rb in your application’s db/migrate directory. Open that file and add to it the following:
db/migrate/001_build_db.rb:
class BuildDb < ActiveRecord::Migration

  def self.up
    create_table :languages, :force => true do |t|
      t.column :name, :string 
      t.column :description, :string 
    end
  end

  def self.down
    drop_table :languages
  end
end
Run this migration script to build the languages table in your database:
$ rake db:migrate
            
Once your database has been created and your Rails application is set up to connect to it, there are two ways to create scaffolding. The first is to use the scaffold
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Speeding Up Rails Development with Mongrel
You want to start hacking on your Rails project in development mode using something faster than the built-in web server, WEBrick.
An excellent alternative to WEBrick is Mongrel. Mongrel is noticeably faster than and is much easier to install than the LightTPD/FastCGI combo. You’ll need a working build environment to install Mongrel on Linux or Mac OS X. Windows users get a precompiled gem. Users of Debian-based Linux distributions will need the ruby-dev and build-essential packages installed, and Mac OS X users should have Apple’s XCode Tools. Once the prerequisites are satisfied, install Mongrel using RubyGems:
$ sudo gem install mongrel
            
Then from your application root, start Mongrel as a daemon (a background process):
$ mongrel_rails start -d
            
Your application is now available on port 3000, the same as the WEBrick default (). To stop the server, type:
$ mongrel_rails stop
            
Mongrel is a fast web server written in Ruby with C extensions. It’s easy to install and can serve as a simple development server, or it can be clustered behind a load balancer for larger, production applications. Mongrel can be used with other Ruby frameworks as well, such as Og+Nitro and Camping, but it is most popular as a solution to the problem of deploying Rails applications. It’s likely that script/server will support Mongrel in the near future, as well as WEBrick and LightTPD.
The solution demonstrates Mongrel running as a daemonized process. You can also run it in the foreground, but you won’t see the same useful output as you do with WEBrick. To get at this information, give the command:
$ tail -f log/development.log
            
Installing the Mongrel plug-in adds the mongrel_rails command to your path. For a list of available options, type that command by itself:
$ mongrel_rails
Usage: mongrel_rails <command> [options]
Available commands are:

 - restart
 - start
 - stop

Each command takes -h as an option to get help.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Enhancing Windows Development with Cygwin
Although you do most of your development on Windows, you’re aware of the tools available under Linux and OS X, including the GNU development tools. You want a way to incorporate these tools into your Windows environment.
Download and install Cygwin fromhttp://www.cygwin.com. Once installed, running Cygwin may look similar to the default Windows terminal program (cmd.exe). What you’ll find though, is that it’s a much more powerful command-line environment from where you can launch hundreds of other useful development tools.
Point your browser tohttp://www.cygwin.com/setup.exe to install a setup program that walks you through the Cygwin install. The program asks a few questions about your environment: for example, which users you want to make Cygwin available to, and what network settings you want the installer to use when downloading packages.
Next, you’ll be presented with a long list of packages. Specify which ones you want to install on your system. Many of these packages are deselected by default, so to change the default installation options for a package, click in the New column for a specific package. Doing so toggles between skipping the package or installing a specific version (sometimes several versions are available).
Once you’ve completed the installation wizard, you can always rerun it and go get packages that weren’t installed initially.
Cygwin makes it possible to have a GNU/Linux-like environment within Windows. Users who are productive with the Unix/Linux command line, but find themselves using Windows for one reason or another, should install Cygwin before doing anything else.
Cygwin makes almost 800 software packages available to you under Windows, and best of all, they’re all free. For a complete and current list of the available packages, visit http://cygwin.com/packages.
The Cygwin installation is definitely unobtrusive software. If you decide it’s not for you or that you want to remove some installed packages, you can easily remove packages from the directory you specified for packages or remove the main Cygwin directory (something like
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Understanding Pluralization Patterns in Rails
You’ve noticed that Rails relies heavily on convention. In particular, it often uses pluralization to link the name of a database class to the corresponding model and controller classes. You want to understand where pluralization is used and where it isn’t.
There are three main places in Rails where pluralization conventions are used by default:
Database table names: plural
Database table names are expected to be pluralized. For example, a table containing employee records should be named Employees.
Model class names: singular
Model class names are the singular form of the database table that they are modeling. For example, an Employee model is created based on a table named employees.
Controller class names: plural
Controller class names are pluralized, such as EmployeesController or AccountsController.
Becoming familiar with these three conventions will go a long way toward getting comfortable with Rails. The intent of pluralization is to make your code more readable and transparent. For a good demonstration of how readable Rails code can be, look at the setup of a one-to-many relationship between chapters and recipes:
app/models/chapter.rb:
class Chapter < ActiveRecord::Base
  has_many :recipes
end
This code reads: “A chapter has many recipes.” You can see how this goes a long way toward explaining the underlying relationship between chapters and recipes. It’s clear enough to nonprogrammers or clients.
There are other places where Rails uses pluralization, including view directory names, functional and unit test filenames, and test fixture filenames.
One of the best ways to get used to pluralization is to experiment with Rails generators while using the --pretend option (or simply -p) when using script/generate to create scaffolding, controllers, or models.
$ ruby script/generate scaffold -p recipe
      exists  app/controllers/
      exists  app/helpers/
      create  app/views/recipes
      exists  test/functional/
  dependency  model
      exists    app/models/
      exists    test/unit/
      exists    test/fixtures/
      create    app/models/recipe.rb
      create    test/unit/recipe_test.rb
      create    test/fixtures/recipes.yml
      create  app/views/recipes/_form.rhtml
      create  app/views/recipes/list.rhtml
      create  app/views/recipes/show.rhtml
      create  app/views/recipes/new.rhtml
      create  app/views/recipes/edit.rhtml
      create  app/controllers/recipes_controller.rb
      create  test/functional/recipes_controller_test.rb
      create  app/helpers/recipes_helper.rb
      create  app/views/layouts/recipes.rhtml
      create  public/stylesheets/scaffold.cs
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Developing Rails in OS X with TextMate
You use Mac OS X and want a GUI-based text editor that makes Rails development productive and enjoyable.
TextMate is the GUI text editor of choice for most Rails developers running OS X (http://macromates.com). TextMate is not free software but can easily be paid for with one or two hours of Rails consulting work.
TextMate is the editor used by the entire Rails core development team. In fact, it’s probably responsible for creating a majority of the Rails code base. TextMate comes with Ruby on Rails syntax highlighting and a large number of macros that let you enter commonly used Rails constructs with just a few keystrokes.
Almost every option in TextMate can be triggered by a combination of keystrokes. This allows you to memorize the actions that you do most often and minimizes the need for mouse movements. Like many native OS X applications, TextMate uses Emacs-style key bindings while editing text. For example, typing Ctrl+A takes you to the beginning of the current line, Ctrl+K deletes from the cursor position to the end of the current line, etc.
TextMate opens a single file with a deceptively simple looking window, but it also has excellent support for projects (directories containing multiple files, subdirectories, etc.) such as Rails projects. Opening a Rails project in TextMate is as simple as dragging the folder and dropping it on the TextMate icon in the dock. Doing so opens TextMate with the project drawer visible. You can explore the files in your project by expanding directories in the project drawer and opening each file into its own tab in the edit window.
shows a Rails application in TextMate’s project drawer. Also visible is the Go to File window that you open with Option+T. This window lets you switch quickly between files in your project.
Figure : A Rails project opened in TextMate
TextMate is extendable through built-in or third-party packages called
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Cross-Platform Developing with RadRails
You want an integrated development environment, or IDE, for developing your Rails applications that is cross-platform, full-featured, and Rails-friendly.
Download and install RadRails (http://www.radrails.org).
Installing RadRails requires Ruby 1.8.4, Rails 1.1+, and Java 1.4+ to be on your system. Once these prerequisites are met, you simply download, extract, and run the RadRails executable to get started.
After reading a few dozen posts from the Rails blogosphere, you may be wondering if there are any IDEs for Rails development other than TextMate. Luckily, for people without Macs (or who just prefer an alternative) there’s RadRails.
RadRails is a Rails-centric IDE built on top of the Eclipse project. Eclipse is a platform-independent software framework for delivering what the project calls rich-client applications. Because Eclipse, and therefore RadRails, is Java-based, it’s a cross-platform development option for whatever OS you happen to be running.
RadRails includes dozens of features, all designed to ease Rails development. It includes a graphical project drawer, syntax highlighting, built-in Rails generators, a WEBrick server, and more. A built-in browser lets you interact with your applications without leaving the IDE.
Included with RadRails is an Eclipse plug-in called subclipse. Subclipse provides an easy-to-use, graphical frontend to the Subversion source control management system. Subclipse lets you perform common Subversion commands in a right-click (option-click for Macs) menu off of each file or directory in the project drawer.
The database perspective allows you to inspect the structure and contents of your database. You can execute queries against your data from within a Query view.
show RadRails displaying the Rails welcome page.
Figure : A Rails project opened and running in RadRails
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Installing and Running Edge Rails
You want to download and run the latest, pre-release version of Rails, known as Edge Rails.
From the root of your Rails application, type:
$ rake rails:freeze:edge
            
When that command finishes, restart your server, and you’ll be running your application on Edge Rails.
If your project is under revision control with Subversion, you can take advantage of Subversion’s externals definitions to instruct it to fetch the contents of a specified subdirectory from a separate repository. To do this, set the svn:externals property with the svn propedit command:
$ svn propedit svn:externals vendor
svn propedit opens your default editor (as indicated by the EDITOR environment variable) on an empty page. In that page, type the following value for svn:externals:
               rails http://dev.rubyonrails.org/svn/rails/trunk/
            
When you save the file and exit the editor, you’ll see the message:
Set new value for property 'svn:externals' on 'vendor'
You then want to check in the property change you just made on the vendor directory and optionally verify that the property was set:
$ svn ci -m 'modified externals on vendor 
               to fetch from the Rails trunk'
Sending        vendor

Committed revision 4.
$ svn proplist --verbose vendor
Properties on 'vendor':
  svn:externals : rails http://dev.rubyonrails.org/svn/rails/trunk/
With the externals property set on vendor, the next time you update your project with svn, the vendor directory will pull down the latest Rails version from the trunk:
$ svn update
            
Edge Rails is the term used for the latest, most cutting-edge version of Rails. (In other words, the version that’s currently under development by the Rails core team.) Normally, a new Rails application uses the Rails packages in the gem path of your Ruby installation. The rake rails:freeze:edge command performs a Subversion export of the last version of Rails from the public subversion repository (
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Setting Up Passwordless Authentication with SSH
You are constantly logging into remote servers throughout the day, and each time you are prompted for your password. Not only is this a drag, but it’s also somewhat of a security risk.
A better alternative to entering passwords for each of your servers is to use cryptographic authentication with SSH public/private key pairs.
Generate a public/private key pair with:
$ ssh-keygen -t dsa
            
You can just hit Enter through all the questions for now. You can alway rerun the command later if you decide to change the defaults.
Now, install your public key on the remote server of your choosing with the command:
 $ cat ~/.ssh/id_dsa.pub | ssh rob@myhost "cat >> .ssh/authorized_keys2"
            
Replace myhost with the domain name or IP address of your server.
A common problem you may encounter with this is incorrect permissions on the .ssh directory and the files therein. Be sure that your .ssh directory and the files in it are readable/writable only by their owner:
$ chmod 700 ~/.ssh
$ chmod 600 ~/.ssh/authorized_keys2
            
The advantage of passwordless authentication is that passwords can be sniffed over the wire and are subject to brute force attacks. Cryptographic authentication eliminates both risks. You also are less likely to make the mistake of leaving your password in your local logs from failed login attempts.
As with most security-related issues, there are always trade-offs. If you store your private key on your local machine, anyone who has access to your machine can potentially gain access to your servers without needing to know your passwords. Be aware of this potential vulnerability when you leave your computer unattended and when you’re considering a security plan.
Additional content appearing in this section has been removed.
Purchase this book now or read it online at Safari to get the whole thing!
Generating RDoc for Your Rails Application