Chapter 1. Introduction

Where, where lieth the fatally named, intractable Ajax?

Sophocles

Purely in terms of buzz, two of the hottest web-development terms in recent memory are Ajax and Rails. Ajax was just coined in February 2005, and seemingly overnight it sparked summits, workshops, books, and articles aplenty. At the beginning of that year, Rails was still a newborn getting scattered discussion in developers’ weblogs. Almost two years later, it claims hundreds of thousands of downloads, nine slashdottings, two conferences, and tens of thousands of books sold.

Why all the noise? Are these technologies fads or worthy of lasting attention?

There are solid reasons to believe that both Ajax and Rails will be significant features of the web development landscape for some time. Big players are leading by example: Yahoo, Google, Apple, Microsoft, and IBM have all started using and touting Ajax techniques, and Rails has become so associated with web startups that it’s almost cliché. And for each high-profile implementation, there are dozens created for smaller audiences or for internal use. As awareness of both technologies grows and they prove their value, the snowball will only roll faster.

Ajax on Rails is the definitive guide to where these two technologies converge.

Who This Book Is For

This book will help you use Rails for building richly interactive web applications with Ajax. It provides comprehensive reference and detailed examples for every JavaScript method that Rails offers, as well as its JavaScript-generating methods. More than just recipes, you’ll also get a thorough, low-level understanding of what’s happening under the hood. And beyond the how-to, we’ll spend time considering when Ajax is (and isn’t) appropriate and the trade-offs associated with it.

This book is written for developers who have experience building for the Web—working knowledge of HTML, CSS, and JavaScript is assumed. Using Rails will require some use of the command line, so you should be familiar with those facilities of your operating system. If you are new to Rails, this book provides a quick introduction, the big picture, a walk through the installation process, and some tips on getting started. But to develop full applications, you’ll benefit from a good guide to Ruby itself, as well as the other Rails components. Fortunately, there are many great tutorials and references available online and in print to fill those needs, and we’ll point you to the best.

If you have started working with Rails and seek to deepen your skill set, this book will do just that. You’ll find dozens of examples drawn from real-world projects, exhaustive reference for every relevant feature, and expert advice on how to “Ajaxify” your applications.

What Ajax Is

Ajax represents a significant shift in how the Web is built—and even in how it’s conceived. But it’s a really simple idea: web pages, already loaded in a browser, can talk with the server and potentially change themselves as a result. So instead of a form submission causing a whole new page to load, an Ajax form submission happens in the background and just updates the current page in place—no refresh, no flash of white as the page changes, no change in the address bar. That’s the essence of Ajax, in the concrete. It’s really that simple! While keeping in mind that simple, concrete definition of Ajax, let’s take a minute to look at Ajax in a more abstract way. First, consider how the Web traditionally works.

The Traditional Model

Think about the way the Web usually works, without Ajax. First, the browser creates an HTTP request for something on the server, say /page1.html. Figure 1-1 shows the life cycle of the request.

The traditional (non-Ajax) request model
Figure 1-1. The traditional (non-Ajax) request model

In this model, the server sends back a response containing a page—perhaps including a header area with a logo, a sidebar containing navigation, and a footer. With the next click on a link or button, the whole cycle repeats for /page2.html: a new connection to the server, a new request, and a new page. Even the parts of the page that haven’t changed (say, the header and sidebar) are sent over the wire again. The process of sending the request, waiting for the response, and rendering a new page might take a while, and once the user has clicked, he’s effectively committed to that wait before he can proceed.

This model works fine, to a point. In fact, when the nature of your site is primarily document-centric, it’s quite desirable. But when developing web applications, it’s a bit heavy—small interactions that ought to feel responsive are sluggish instead. For example, imagine a web application for managing to-do lists. If simply checking an item off the list causes the entire page to be re-fetched and rendered, the cause and the effect are pretty disproportionate.

The Ajax Model

Remember how simple Ajax is in concrete form: it’s just pages talking with the server without a full refresh. With that in mind, contrast the traditional request model with the Ajax model, as seen in Figure 1-2.

The Ajax request model
Figure 1-2. The Ajax request model

In the Ajax model, the action on the client side is split into two logical parts—a user interface layer and an Ajax layer. When a user clicks a link, or submits a form, that input is handed to the Ajax layer, which could then interact with the server, and update the UI layer as appropriate.

This is the conceptual cornerstone of Ajax: the UI interaction is logically separated from the network interaction.

There are a few important points to draw from the diagram of the Ajax model:

  • The Ajax layer might not need to call the server (for example, it might only need to perform simple form validation, which could be handled completely client-side).

  • Because the requests between the Ajax layer and the server are for small pieces of information rather than complete pages, there is often less database interaction, rendering time, and data to transport—making the round-trip time for the request shorter.

  • The UI layer is not directly dependent on the server’s responses, so the user can continue to interact with a page while activity is happening in the background. This means that, for some interactions, the user’s wait time is effectively zero.

  • Communication between the page and the server doesn’t necessarily imply that Ajax always results in a change to the UI. For example, some applications use Ajax to notify the server about the user’s interactions with the page, but don’t do anything with the server’s response.

These fundamental differences from the traditional request cycle are what enable Ajax applications to be significantly more responsive. And that means that web applications can start to perform like desktop applications—and retain all the benefits of being hosted, rather than installed locally.

It’s Actually Pretty Easy

If the Ajax model just described sounds like a lot of work, don’t fret. In practice, Ajax is very easy to be productive with, especially in Rails. To pique your interest and whet your appetite, here’s a tiny example of how much can be accomplished with very little code. Don’t worry if the syntax is unfamiliar—just focus on the intent of the code.

There are two files in this example: pique.rhtml uses HTML with embedded Ruby statements to create a simple “Ajaxified” form; whet.rjs receives the form submission and updates the page in response. Here’s the first file, pique.rhtml:

<%= form_remote_tag :url => { :action => 'whet' } %>
  Enter your name: <%= text_field_tag :name %>
  <%= submit_tag "Greet Me" %>
<%= end_form_tag %>
<h2 id="greeting" style="display: none"></h2>

This code creates a familiar-looking HTML form with one field and a submit button, as well as a hidden HTML heading (see Figure 1-3). When the form is submitted, it will use Ajax to invoke the second file, whet.rjs:

A simple Ajax form
Figure 1-3. A simple Ajax form
page[:greeting].hide
page[:greeting].update "Greetings, " + params[:name]
page[:greeting].visual_effect :grow
page.select("form").first.reset   

These four lines of code pack a wallop—they are instructions telling the page how to update itself. Taking it one line at a time, the instructions are:

  1. Hide the element called “greeting” (in case it’s not already hidden).

  2. Update the element—that is, replace the text inside the tags with some new text.

  3. Show it again, animating it onto the screen with a zoom effect.

  4. Find the first form on the page and reset it, so that the input field is blank again.

The end result after submitting the form is shown in Figure 1-4. Note that the address bar hasn’t changed—that’s because the page wasn’t replaced with a new one, it was just updated in place.

After submitting the Ajax form
Figure 1-4. After submitting the Ajax form

If you’re surprised at how little work is needed to get such impressive results, welcome to Ajax on Rails.

The Eras of Web Development

The web has only been a mass phenomenon since about 1995, so for many developers, it’s not hard to remember how we got here. Still, in order to understand the significance of Ajax, it’s valuable to look back at the big themes. At the risk of being overly grand, let’s compare the history of the Web to the history of the world. Historians organize time into a handful of eras—long periods with distinctive, defining characteristics. With a bit of hyperbole and broad-brushing, the same divisions can be used to understand the eras of web development.

First, there’s pre-history, the earliest days, before writing was invented, before civilization. In web terms, Tim Berners-Lee sparked the big bang with his WorldWideWeb program. His vision centered on hypertext, the idea that individual phrases in a document could be linked to other documents. This first incarnation of the Web would hardly be recognized today. All text—no images, colors, or font choices. All static—no forms, CGI, or JavaScript. And in terms of content, almost all academic and scientific—no e-commerce, no advertisements, and no news. Despite the huge differences, however, the three pillars of the Web were in place: HTTP, HTML, and URLs.

The next major milestone in world history was the transition to the ancient era—the dawn of civilization. People formed ever-larger communities, and they developed increasingly complex systems and institutions to support the growth. For our purposes, the ancient Web begins with Mosaic, the first web browser to really show the Web’s potential. Its biggest innovation: the introduction of the <img> element. Suddenly, the Web burst into color, and with color came personality. Personal home pages became de rigueur, and the pulse of the Web quickened.

Next came the Middle Ages—that long, vibrant period of migration, growth, and invention. The Web analog might be summed up as “the David Siegel ages”—the Web designer who popularized the “single-pixel GIF trick” and deeply nested HTML tables. This era also saw the first <font>, the birth of the banner ad, and the explosion of e-commerce.

Most web developers today live in the modern era. The biggest signpost is standards: CSS has come to the fore, and web designers are un-learning the markup hacks that are no longer necessary. Although far from perfect, the most popular browsers are increasingly compatible and reliable.

Now, the stage is set for the latest act, the postmodern era. Old assumptions and institutions are questioned, which generates exciting energy, along with turmoil. In web terms, the biggest keyword here is Ajax. The core idea of Ajax is that the Web is no longer page-centric. Rather, individual chunks of a page are dynamic and malleable, independent of each other. It’s a simple concept, but it has profound implications, and requires rethinking our assumptions about how the Web should be built.

History of Ajax

Although the name is relatively new, the ideas behind Ajax have been brewing for some years. Variously called web remoting and remote scripting, the idea is simply communication between the web client and server at a subpage level. There are several ways to accomplish that goal. One of the earliest was Java applets, but that approach suffered under the weight of slow Java implementations and inadequate cross-browser compatibility. A more popular trick uses hidden HTML frames—JavaScript is used to load new data into a hidden frame, before it’s pulled out and parsed. Some high-profile sites (such as Google Maps) use this technique, although it has drawbacks, such as no reliable error detection.

Today, the most popular solution for building Ajax applications is an unfortunately named object, XMLHttpRequest. In its original implementation by Microsoft, it was an ActiveX object called XMLHTTP. Since its debut in Internet Explorer, other browsers have cloned it as XMLHttpRequest, including Firefox (and its relatives, Netscape and Mozilla), Safari, and Opera. Of course, this wouldn’t be the Web if each browser didn’t have its own pesky quirks. But nonetheless, most major browsers today have good support for XMLHttpRequest—and that opens up a lot of possibilities.

An oft-heard complaint about the term Ajax is that it’s merely a new marketing term for old techniques. And in fact, that’s exactly correct. When Jesse James Garrett coined Ajax (http://www.adaptivepath.com/publications/essays/archives/000385.php), it was explicitly for the purpose of putting an accessible label on a broad swath of technologies that had been in use for years. After all, when you are pitching an idea to a client or a boss, complex solutions need a simple term that makes it easy to talk about.

Ajax: Neither Asynchronous nor XML. Discuss.

Although it’s not strictly an acronym, let’s break down Ajax into its literal parts: asynchronous, JavaScript, and XML.

Asynchronous refers to the fact that, by default, XMLHttpRequest calls are nonblocking; that is, the browser can initiate a request, and then keep executing code without waiting for the response to come back. If it weren’t for that fact, the Ajax experience would be far less pleasant—if the network or server were slow, your browser would seem to freeze while it waited on a response. Asynchronicity is essential to providing a smooth user experience, but it can complicate the programming. Occasionally, there are circumstances when you don’t want Ajax calls to be asynchronous, when the user shouldn’t have any interaction until a response is returned from the server. XMLHttpRequest and Rails handle that just fine. So, despite its name, Ajax is not necessarily asynchronous.

The J in Ajax stands for JavaScript. JavaScript is a powerful language that is often abused and unfairly maligned. It’s the only scripting language that’s supported more-or-less uniformly across all modern browsers, so it’s immensely useful for manipulating web pages on the client side.

Originally called LiveScript, marketing folks at Netscape changed the name in order to associate it with Java—even though the two languages have no real relationship. These days, the official, vendor-neutral name of the language is ECMAScript, but in popular usage JavaScript has stuck.

JavaScript has a bad reputation among many web developers, because it’s associated with amateurish, brittle, cut-and-paste scripts. Historically, development-support tools for JavaScript, such as debuggers and loggers, also have been weak, making JavaScript development frustrating at best. The good news is that JavaScript can be far nicer than its reputation would suggest. With a combination of quality libraries, development support tools, and some practices for writing solid code, JavaScript can be a surprisingly agreeable platform.

Although JavaScript may be the most ubiquitous language for client-side scripting, it’s not the only option. Internet Explorer supports Visual Basic scripts in the browser, and Flash provides widely deployed, cross-platform scripting. And both environments allow calls to the server, meaning that the J in Ajax isn’t a necessity either.

That brings us to the X, as in XML. As you can probably guess, it turns out this isn’t really an Ajax absolute either. The XMLHttpRequest object can easily handle content of any type— XML, HTML, plain text, images, anything. In fact, as we’ll see, Rails applications rarely request XML data via Ajax. Most often, Rails apps use HTML and JavaScript as the format for Ajax responses.

A couple of other things contribute to the essence of Ajax as well, namely the Document Object Model (DOM) and CSS. The DOM is a language-neutral interface for accessing HTML and XML documents. Before the DOM was standardized, each browser had its own methods for accessing page elements from JavaScript. CSS is essential for allowing appealing graphic design without sacrificing the semantic structure of HTML documents.

So, if you’re a literalist, feel free to refer to this book as [AS]|[JFV]A[XHJ] on Rails. But I’d suggest a redefinition of Ajax in terms of the problems it solves, rather than the exact technologies used. For the purposes of this book, Ajax is the use of browser-native technologies (e.g., JavaScript and the DOM, but not Flash) to decouple user interaction processes from server communication processes.

It’s worth noting that this definition of Ajax isn’t universally accepted. Many developers feel that Ajax necessarily implies use of XMLHttpRequest, and that any other use of the word is a conflation with plain JavaScript. But even Jesse James Garrett’s article introducing the term cited client-side form validation as an example of Ajax.

Regardless of what words are used, the important thing is using the tools at hand to provide the best possible experience for the user—and that’s the goal of this book.

What Rails Is

So far, we’ve been thinking about Ajax; let’s shift now to Rails. Ruby on Rails (or more commonly, just Rails) is a full-stack MVC web development framework for the Ruby language. That’s a mouthful. Let’s break down the concepts one by one:

Full-stack means that the framework encompasses almost everything you’ll need to create a finished product. It’s perhaps a bit of a misnomer, because most applications will also require a persistence layer (a database) and a web server. But at the application level, Rails has everything needed by most projects, most of the time—there’s no need to select an additional templating system or database-mapping system.

MVC stands for Model View Controller, which is simply a way of organizing your application into chunks, according to their responsibility.

  • The model represents your domain objects (such as User, Company, Post, etc.) and interacts with the database.

  • The view deals with the user interface: generating HTML, RSS feeds, JavaScript code, etc.

  • The controller handles user input and orchestrates interaction between the model and the view.

Web applications don’t have to be organized according to MVC—many developers freely mix all three parts. But as systems get larger, the mixed-up method quickly becomes untenable and prone to error. Code can be organized lots of ways, but MVC is the Rails way and a time-tested approach to keep your application maintainable.

A framework can be seen as a set of constraints for your program. At first, that sounds like a bad thing—why constrain yourself? But it turns out that by embracing constraints for a specific purpose, you actually enable creativity, by focusing energy on the problem at hand. The Rails framework is a set of constraints that enables effective web development.

When I was in college, I studied in Paris for a while, and I often visited cyber cafés to write friends back in the U.S. The experience introduced me to non-English keyboard layouts. Usually they were French, but I also ran into German and Spanish. The layouts of all the keyboards are similar, but just different enough to be a hassle—a few letters swapped here and there, slowing down my typing tremendously. One day, while emailing a friend, I was unable to find a way to type the letter m for the life of me.

That’s when I discovered the joys of lipograms: compositions in which one or more letter is intentionally omitted, just for the challenge. So that day I wrote a reluctant lipogram, and I’ve been fascinated with them since. Take the novel Gadsby by Ernest V. Wright, written entirely without the letter e. Here’s the first sentence:

If Youth, throughout all history, had had a champion to stand up for it; to show a doubting world that a child can think; and, possibly, do it practically; you wouldn’t constantly run across folks today who claim that ‘a child don’t know anything.’

Lipograms are about imposing artificial constraints. The interesting thing about writing them is the side effect: they force you to think more creatively about the problem of communication. When you deny yourself complete freedom in writing, it often actually allows you to express yourself better. Lipograms are an extreme example, but poetry and lyrics work the same way. Often the reason they have so much expressive power is because the writer is limited metrically or in rhyme.

Working in the Rails framework exhibits the same paradox. By embracing constraints and voluntarily giving up freedom along some axis, you enable a great deal of creative and productive power.

Ruby is an elegant, object-oriented, dynamically typed programming language, with roots in List, Perl, and Smalltalk. Its creator, Yukihiro “Matz” Matsumoto, has said Ruby is “optimized for programmer joy.” Ruby has been around since 1995 and, pardon the cliché, is quite big in Japan. But until Rails’ catalytic effect, it didn’t receive much attention in the West. Because Rails’ power is so closely tied to Ruby’s expressiveness, it can be hard to separate the two. It was no accident that David Heinemeier Hansson (or DHH, as he’s affectionately known), the creator of Rails, acknowledged his debt to Ruby right in the framework name, Ruby on Rails.

Rails Mantras

The Rails community has a number of mantras, guiding principles for its development. Understanding them goes a long way toward understanding Rails.

Frameworks are extractions

This mantra is, at heart, a story about the genesis of Rails. That genesis is Basecamp, the project-management application created by 37signals (http://www.basecamphq.com). As DHH created Basecamp, he gradually extracted infrastructure-related code out of the application code, and into the framework. The result was that the framework was shaped directly by real-world problems, rather than conceived in the abstract. The ongoing effect of this philosophy is that the Rails core developers expect additions to Rails to be drawn from real-world needs, not hypothetical ones. As a result, you won’t find a grand road map or five-year plan for Rails’ development—framework features are always extracted from applications.

Convention over configuration

For developers who have experience with other web frameworks, this idea often provides the biggest pleasant surprise. Other frameworks often require hundreds of lines of configuration code (usually in the form of XML files) before an application is usable—explicit mappings between URLs and methods, between model attributes and database columns, etc. The mantra of convention over configuration suggests that whenever possible, explicit configuration should be replaced by sensible defaults. Take database mapping, for example. Suppose you have a couple of database tables, users and projects, and you’d like to model a one-to-many relationship between the database tables. The Ruby code needed to create models for those tables might look like:

class User < ActiveRecord::Base
  has_many :projects
end

class Project < ActiveRecord::Base
  belongs_to :user
end

That’s really it! Notice that Rails uses introspection to take the class names User and Project and infers the lowercase plural forms for the table names users and projects. You might also be wondering how Rails knows how to relate the two models like it does. The answer is another case of convention over configuration: it assumes that the projects table has a column called user_id. Of course, it’s easy to override any of the defaults that Rails assumes, as need or preference dictate—convention never replaces configuration. But following the provided conventions has a lot of benefit.

Opinionated software

This mantra is related to the last one. Every piece of software is opinionated—it encourages (and discourages) certain ways of thinking, of solving problems, of structuring ideas. Software embodies a vision of the world. However, not all software acknowledges its opinions or strongly defines its vision. In fact, many pieces of software go out of their way to appear neutral on matters of style and practice. Rails takes the opposite approach—it has a strong vision and makes its opinions about web development very clear. Take the example above, for instance. Rails promotes the opinion that models generally ought to correspond one-to-one with database tables with plural names and a single surrogate primary key column, named id. It’s certainly possible to work around the framework’s opinion on that issue, but it will involve more work.

Don’t repeat yourself

Another important Rails philosophy is called the DRY principle, or don’t repeat yourself. Although it’s often misunderstood, the idea is simple: every piece of knowledge in your system ought to have one authoritative representation. Every developer knows why this is important, if she has ever had to search through a program to find all the places where one assumption is hardcoded in. But notice that knowledge is a broad term—it covers more than just lines of code. It envelops data structures, documentation, and even fuzzier concepts like intention. Mastering DRY takes effort and experience, but Rails paves the way.

‘You Got Your Ajax in My Rails!’

We’ve now looked at what Ajax is and what Rails is. But this book is about both of them together and how these two great tastes complement each other.

As discussed above, one of Rails’ mantra is frameworks are extractions. And the story of Ajax in Rails exemplifies that philosophy perfectly. During the development of another 37signals product, TaDa List (http://www.tadalist.com), the developers needed some simple Ajax functionality. Writing the necessary JavaScript for the project turned out to be painful—and pain is often the first sign that an extraction might be useful. By the time the company embarked on its next Ajax/Rails application, Backpack (http://backpackit.com), Ajax functionality had been added to the framework. The result was that Rails was one of the first web frameworks with first-class Ajax support. And because of the philosophy of extraction, it remains one of the most pragmatically useful environments to work in.

There are two sides to the Ajax/Rails coin. The first is composed of two JavaScript frameworks: Prototype and script.aculo.us. Both are bundled with and developed alongside Rails, although they can readily be used with applications in other languages, such as PHP and Java. Prototype provides convenient wrappers around XMLHttpRequest, as well as a wealth of methods for manipulating the DOM and JavaScript data structures. The script.aculo.us library builds atop Prototype and focuses on visual effects and advanced UI capabilities, such as drag and drop.

Rails helpers represent the flip side of the coin. These are Ruby methods, called from within the controller and view code that (among other things) generate bits of JavaScript that in turn invoke Prototype and script.aculo.us. The end result is that it’s possible to create very rich “Ajaxified” applications without writing any JavaScript.

Getting Up to Speed

If you haven’t yet started using Ruby or Rails, this section will point you in the right direction. If you’re comfortable with Rails basics, feel free to skip ahead to Chapter 2, where we’ll start doing Ajax. It’s outside the scope of this book to provide a comprehensive guide to Ruby, or all of Rails. Fortunately, there are dozens of excellent resources available to fill that need. In this section, we’ll point you to the best.

Starting Ruby

Getting and installing Ruby is easy on almost every platform. The official web site is http://ruby-lang.org. From there, you’ll find downloads for the latest releases. Windows users can take advantage of the One-Click Ruby Installer (http://rubyinstaller.rubyforge.org), which bundles lots of great extensions. Mac users already have Ruby installed as part of OS X—however, it’s not configured correctly for Rails use. To fix that, follow this guide: http://hivelogic.com/articles/2005/12/01/ruby_rails_lighttpd_mysql_tiger.

Ruby has a solid (and quickly growing) body of documentation, suited to all experience levels. Here are some of the best resources:

  • The Ruby web site (http://ruby-lang.org) is the home base for English-language resources on Ruby—including downloads, documentation, and news.

  • Try Ruby (http://tryruby.hobix.com) is a hands-on Ruby tutorial that runs entirely in your browser, with no need to download Ruby first. It’s a great way to familiarize yourself with Ruby’s syntax and conventions.

  • Programming Ruby by Dave Thomas, et al. (Pragmatic Bookshelf), also known as the “Pickaxe book,” is the most popular book on Ruby, for good reason—it’s full of clear explanations and vital reference. Best of all, the first edition (which doesn’t cover the latest additions to Ruby but is still immensely useful) is available free online at http://www.rubycentral.com/book.

  • Why’s (Poignant) Guide to Ruby (http://poignantguide.net/ruby) is a great, free resource for learning Ruby. Self-described as “the pirate radio of technical manuals,” it also serves as an excellent introduction to the off-the-wall sense of humor often found in the Ruby community.

  • ruby-talk is the official Ruby mailing list. As you delve into Ruby, it’s invaluable to have access to a community of fellow developers, and ruby-talk is just that. To subscribe, send a message to ruby-talk-ctl@ruby-lang.org with subscribe Your-First-Name Your-Last-Name in the body of the message.

  • #ruby-lang is an IRC channel that’s regularly buzzing with enthusiastic and helpful Rubyists. Just grab any IRC client and connect to irc.freenode.net.

  • Ruby Core and Standard Library documentation is available from the Rails web site: http://corelib.rubyonrails.org and http://stdlib.rubyonrails.org. It’s not organized linearly for beginners, but it’s fantastic for reference.

Getting on the Rails

Once you have Ruby installed, installing Rails is another simple process.

  1. First you’ll need RubyGems, Ruby’s standard package-management system. You can download the latest version from http://docs.rubygems.org. Once you extract it, just run ruby setup.rb from your system’s command line to install it.

  2. Install Rails and its dependencies by entering gem install rails -y. If you’re using a Unix-like system, you may need to run gem as root, or by using sudo. While you’re at it, run gem install mongrel -y as well—Mongrel is a speedier alternative to Ruby’s built-in web server.

As in the general Ruby community, there are a fast-growing number of resources available for learning Rails:

  • Agile Web Development with Rails by Dave Thomas, et al. (Pragmatic Bookshelf) was the first Rails book; it was co-written by Dave Thomas and David Heinemeier Hansson. It’s chock-full of clear examples and helpful tips.

  • The Rails API Documentation is available at http://api.rubyonrails.org. It can be somewhat terse and hard to navigate until you understand how Rails is organized, but it’s an invaluable reference for how particular methods work. One of its best features is that it allows you to view the source for each method in the API—a fantastic way to learn about Rails internals and good Ruby style, as well.

Tip

When you install Rails, a copy of the Rails API Documentation is installed on your local computer along with it, which is handy for working offline. To access it, run gem_server from the system command line, and a Ruby web server will be started on port 8808. Then browse to http://localhost:8808 and you’ll see a list of every package installed via RubyGems.

  • The #rubyonrails IRC channel is great resource for interacting with other Rails developers. As with #ruby-lang, just use any IRC client and connect to irc.freenode.net.

  • The Rails Wiki (http://wiki.rubyonrails.org/rails) is full of user-contributed hints and tutorials on everything from the basics to the very complex. Unfortunately, it also has a fair amount of outdated advice, but it’s still a great place to start looking for answers.

  • The Rails mailing list is one of the best places to find announcements of new Rails plug-ins and projects, discussion of new features, and troubleshooting of problems. You can browse the archives and subscribe at http://groups.google.com/group/rubyonrails-talk.

Other Things You’ll Want

A database

Rails works with a number of different databases, and the most common are free: MySQL, PostgreSQL, and SQLite. (There are also database adapters included for DB2, Oracle, Firebird, and SQL Server.) Each has its advantages and disadvantages, but if you’re just getting started, it won’t make much difference. MySQL installers for Windows, Mac, and Linux are available at http://dev.mysql.com/downloads/mysql/5.0.html. While you’re at it, you’ll also want a database client program to make it easier to create and modify database tables. For MySQL, the MySQL Query Browser is a good cross-platform option. Get it at http://dev.mysql.com/downloads/query-browser/1.1.html.

A text editor

While any bare-bones text editor will work, developing with Rails involves lots of switching between files, so it’s worth finding a powerful editor. Rails developers on Mac OS X usually use TextMate, available from http://macromates.com. Windows developers often recommend TextPad (http://www.textpad.com) and UltraEdit (http://www.ultraedit.com).

Hello, Rails

If you’ve just installed Rails for the first time, let’s kick the tires. First, from the command line, navigate to where you want to create your first application (perhaps your home directory or your work area). Then, run rails ajaxonrails. The rails command-line program simply generates a skeleton app—all the standard directories and boilerplate files you’ll need for every project. Take a look in the ajaxonrails directory that you just created, and you’ll see the following:

app/ As the name suggests, this is where your Rails-specific application code lives. 
controllers/ Controllers orchestrate your application flow, taking in HTTP requests, interacting with the model, rendering a view, and returning an HTTP response. 
helpers/ Helpers are Ruby methods that are called from the views, to help keep your code clean. Rails includes a lot of helpers, and you can define your own in this directory. 
models/ Models generally correspond directly to database tables, and they encapsulate database functions from the rest of your application. 
views/ We’ll be spending a lot of time in this directory—it’s where your view layer lives, which is responsible for generating HTML, among other things. 
config/ Here you’ll configure your application for its environment, telling it how to connect to a database, how external URLs map to internal code, etc. 
doc/ Rails can automatically generate API documentation for your application’s code; this is where it will go. 
lib/ This directory is intended for custom Ruby libraries that your application requires. 
log/ As your application runs, Rails generates helpful logs in this directory. 
public/ In a typical setup, this is the “document root” of your application, where all static files go (images, JavaScript, CSS, static HTML, etc). 
script/ Every Rails application comes with a default set of standard scripts for generating code, starting and stopping the app, etc. They belong here, along with any other scripts you create. 
test/ Rails encourages the practice of automated testing and puts the boilerplate “stubs” for your test code in this directory. 
tmp/ This directory holds temporary files used by the application—sessions, caches, and sockets. 
vendor/ This directory holds third-party libraries for your application. 
plugins/ This directory holds Rails plugins—packages of code that extend and modify the framework’s features. 

After you have created a skeleton application from the command line, change directories into your project directory (ajaxonrails). Then, run the application by entering script/server. You will see a message indicating the application has started. To shut the server down, use Ctrl-C.

The script/server command invokes Mongrel (or WEBrick, if Mongrel is not installed), a Ruby web server that’s perfect for development purposes. Opening your web browser to the address http://localhost:3000, you should see the Rails welcome screen (Figure 1-5 ). Congratulations, you’re on Rails!

Ruby on Rails: Welcome aboard
Figure 1-5. Ruby on Rails: Welcome aboard

Rails Writ Large

Now that you’ve had a little taste of the practice, here’s the theory. This section is just overview—for the full details on these things, refer to the Rails resources above.

Rails is divided into a handful of libraries: ActiveRecord and ActionPack (the most important two for this book), as well as ActiveSupport, and ActionMailer.

ActiveRecord is an object relational mapper (ORM). ORMs act as a bridge between relational databases and object-oriented languages. Relational databases inherently organize information differently than objects do—for instance, objects are able to encapsulate behavior (methods) as well as data. ORMs exist to address that problem. There are a number of different ways to accomplishORM, including a design pattern called Data Mapper. The Data Mapper approach allows a great deal of flexibility, by allowing you to explicitly define the mappings between your objects and your database tables. ActiveRecord was named after an alternative pattern, Active Record. Compared with Data Mapper, it trades some flexibility (a layer of indirection between the database and the in-memory objects) to gain a lot of simplicity—it automatically creates an object attribute for every database column. Without that feature, you’d have to define your mapping explicitly, which leads to the verbose XML configuration files common in other frameworks.

Three other features of ActiveRecord to note are associations, callbacks, and validations. Associations allow you to define relationships between your ActiveRecord classes, like one-to-one, one-to-many, and many-to-many. Callbacks provide a robust set of hooks into the life cycle of your objects, where you can add behavior (e.g., after a record is updated, create an entry in an audit log). Validations are a special kind of callback that make standard data-validation routines a cinch. By keeping your associations, callbacks, and validation rules in the ActiveRecord class definition, you’re making it easier to create reliable, maintainable code.

ActionPack has two subparts that work together closely, ActionController and ActionView. ActionController classes define actions—public methods that are accessible from the Web. Actions always end in one of two ways: either with a redirect (an HTTP response header sent back, causing the client to be forwarded to another URL) or with a render (some content being sent back to the client, usually an HTML file). When an action renders an HTML file, ActionView is invoked. To see how these major libraries work together, take a look at the life cycle of a typical Rails request in Figure 1-6.

Rails request cycle
Figure 1-6. Rails request cycle

Summary

In this chapter, we looked at the 30,000-foot view of Ajax and Rails. First with Ajax—its basic mechanisms, motivation, and location in the larger historical context of the Web. We deconstructed the strict acronym interpretation of Ajax and replaced it with a definition centered more on solving problems.

Then we shifted attention to Rails, Ruby, and frameworks in general. We discussed the ideals that guide the development of Rails and the history of Ajax in Rails. In the last section, we fired up the terminal and walked through installing Ruby and Rails, and making sure the whole thing works by creating an application skeleton.

In the next chapter, we’ll pick up exactly where we left off and start adding code to the skeleton application.

Get Ajax on Rails now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.