Agile Web Development with Rails A Pragmatic Guide Second Edition Dave Thomas instant download
Agile Web Development with Rails A Pragmatic Guide Second Edition Dave Thomas instant download
https://ebookname.com/product/agile-web-development-with-rails-a-
pragmatic-guide-second-edition-dave-thomas/
https://ebookname.com/product/agile-web-development-with-
rails-5-1-1st-edition-sam-ruby/
https://ebookname.com/product/ruby-on-rails-tutorial-learn-web-
development-with-rails-2nd-edition-michael-hartl/
https://ebookname.com/product/programming-elixir-functional-
concurrent-pragmatic-fun-1st-edition-dave-thomas/
https://ebookname.com/product/not-just-tacos-a-journey-into-the-
world-of-authentic-latin-american-cuisine-first-edition-shirley-
solis/
Quality Equity Autonomy 1st Edition Lee Hwok Aun
https://ebookname.com/product/quality-equity-autonomy-1st-
edition-lee-hwok-aun/
https://ebookname.com/product/ppl-book-3-navigation-2nd-edition-
cae-oxford-aviation-cae-oxford-aviation/
https://ebookname.com/product/dungeons-dragons-for-dummies-1st-
edition-bill-slavicsek/
https://ebookname.com/product/the-last-kingdom-3rd-edition-berry/
Investing in Emerging Markets The Rules of the Game 1st
Edition William Gamble
https://ebookname.com/product/investing-in-emerging-markets-the-
rules-of-the-game-1st-edition-william-gamble/
Important Information
About Rails Versions
Rails is an evolving framework. The core Rails developers are continually
making changes, adding new features, fixing bugs, and so on. Periodically
they package up the latest version of Rails into a release. These releases are
then available to application developers as RubyGems.
As the book is going to press the core team have created the codebase for
Rails 1.2. However, they have not yet packaged it into a gem. This gives us a
bit of a problem. We want the book to reflect all the latest and greatest Rails
features, but we also know that it is hard for folks to jump through the hoops
required to get the so-called Edge version of Rails installed on their systems.
And until a gem is available, the 1.2 features are only available in Edge Rails.
Now, it may well be that by the time you get your hands on this book, the
Rails 1.2 gem is out. It’s easy to find out. After you’ve installed Rails (as
described in Chapter 3, Installing Rails, on page 31), bring up a command
prompt and enter rails -v. If it reports “Rails 1.2” or later, you’re fine.
If instead you see something like “Rails 1.1.6,” you’ll need to update to get
the code in this book to run. We’ve prepared a snapshot of the Rails frame-
work code that we used when writing this book. You can install it in your
own Rails applications as a temporary measure until 1.2 is released.
• Create your application normally. You’ll find that it will contain a direc-
tory called vendor
rake rails:update
Once Rails 1.2 is released, you can install it and remove the directory tree
vendor/rails from your applications.
The version of Rails from our web site is not an official release, and should
not be used in production applications.
Dave Thomas
Agile Web Development with Rails
Second Edition
Dave Thomas
David Heinemeier Hansson
Leon Breedt
with
Mike Clark
James Duncan Davidson
Justin Gehtland
Andreas Schwarz
Every precaution was taken in the preparation of this book. However, the publisher assumes no
responsibility for errors or omissions, or for damages that may result from the use of information
(including program listings) contained herein.
Our Pragmatic courses, workshops, and other products can help you and your team create better
software and have more fun. For more information, as well as the latest Pragmatic titles, please
visit us at
http://www.pragmaticprogrammer.com
No part of this publication may be reproduced, stored in a retrieval system, or transmitted, in any
form, or by any means, electronic, mechanical, photocopying, recording, or otherwise, without the
prior consent of the publisher.
ISBN-10: 0-9776166-3-0
ISBN-13: 978-0-9776166-3-3
Printed on acid-free paper with 85% recycled, 30% post-consumer content.
P2.00 printing, January 15, 2007
Version: 2007-1-8
Contents
Preface to the Second Edition 12
1 Introduction 14
1.1 Rails Is Agile . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 16
1.2 Finding Your Way Around . . . . . . . . . . . . . . . . . . . . . 17
1.3 Acknowledgments . . . . . . . . . . . . . . . . . . . . . . . . . . 19
3 Installing Rails 31
3.1 Your Shopping List . . . . . . . . . . . . . . . . . . . . . . . . . 31
3.2 Installing on Windows . . . . . . . . . . . . . . . . . . . . . . . . 32
3.3 Installing on Mac OS X . . . . . . . . . . . . . . . . . . . . . . . 34
3.4 Installing on Linux . . . . . . . . . . . . . . . . . . . . . . . . . . 35
3.5 Development Environments . . . . . . . . . . . . . . . . . . . . 36
3.6 Rails and Databases . . . . . . . . . . . . . . . . . . . . . . . . . 39
3.7 Keeping Up-to-Date . . . . . . . . . . . . . . . . . . . . . . . . . 42
3.8 Rails and ISPs . . . . . . . . . . . . . . . . . . . . . . . . . . . . 42
4 Instant Gratification 43
4.1 Creating a New Application . . . . . . . . . . . . . . . . . . . . . 43
4.2 Hello, Rails! . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45
4.3 Linking Pages Together . . . . . . . . . . . . . . . . . . . . . . . 56
4.4 What We Just Did . . . . . . . . . . . . . . . . . . . . . . . . . . 59
CONTENTS 6
16 Migrations 263
16.1 Creating and Running Migrations . . . . . . . . . . . . . . . . . 264
16.2 Anatomy of a Migration . . . . . . . . . . . . . . . . . . . . . . . 266
16.3 Managing Tables . . . . . . . . . . . . . . . . . . . . . . . . . . . 270
16.4 Data Migrations . . . . . . . . . . . . . . . . . . . . . . . . . . . 275
16.5 Advanced Migrations . . . . . . . . . . . . . . . . . . . . . . . . 278
16.6 When Migrations Go Bad . . . . . . . . . . . . . . . . . . . . . . 280
16.7 Schema Manipulation Outside Migrations . . . . . . . . . . . . 281
16.8 Managing Migrations . . . . . . . . . . . . . . . . . . . . . . . . 282
CONTENTS 8
D Resources 684
D.1 Online Resources . . . . . . . . . . . . . . . . . . . . . . . . . . 684
D.2 Bibliography . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 684
Index 685
Tous les jours, à tous les points de vue, je vais de mieux en
mieux.
Émile Coué
In the year that followed, Rails went from strength to strength. It was used
as the basis for any number of new, exciting web sites. Just as significantly,
large corporations (many of them household names) started to use Rails for
both inward- and outward-facing applications. Rails gained critical acclaim,
too. David Heinemeier Hansson, the creator of Rails, was named Hacker of the
Year at OSCON. Rails won a Jolt Award as best web development tool, and the
first edition of this book received a Jolt Award as best technical book.
But the Rails core team didn’t just sit still, soaking up the praise. Instead,
they’ve been heads-down adding new features and facilities. Rails 1.0, which
came out some months after the first edition hit the streets, added features
such as database migration support, as well as updated AJAX integration.
Rails 1.1, released in the spring of 2006, was a blockbuster, with more than
500 changes since the previous release. Many of these changes are deeply
significant. For example, RJS templates change the way that developers write
AJAX-enabled applications, and the integration testing framework changes the
way these applications can be tested. A lot of work has gone into extending and
enhancing Active Record, which now includes polymorphic associations, join
models, better caching, and a whole lot more.
The time had come to update the book to reflect all this goodness. And, as I
started making the changes, I realized that something else had changed. In the
time since the first book was released, we’d all gained a lot more experience
of just how to write a Rails application. Some stuff that seemed like a great
idea didn’t work so well in practice, and other features that initially seemed
peripheral turned out to be significant. And those new practices meant that
the changes to the book went far deeper than I’d expected. I was no longer
doing a cosmetic sweep through the text, adding a couple of new APIs. Instead,
I found myself rewriting the content. Some chapters from the original have
been removed, and new chapters have been added. Many of the rest have been
P REFACE TO THE S ECOND E DITION 13
Enjoy!
Dave Thomas
October 2006
Chapter 1
Introduction
Ruby on Rails is a framework that makes it easier to develop, deploy, and
maintain web applications. During the months that followed its initial release,
Rails went from being an unknown toy to being a worldwide phenomenon. It
has won awards, and, more important, it has become the framework of choice
for the implementation of a wide range of so-called Web 2.0 applications. It
isn’t just trendy among hard-core hackers: many multinational companies are
using Rails to create their web applications.
But easy on its own doesn’t cut it. We’re talking about professional developers
writing real-world web sites. They wanted to feel that the applications they
were developing would stand the test of time—that they were designed and
implemented using modern, professional techniques. So these developers dug
into Rails and discovered it wasn’t just a tool for hacking out sites.
For example, all Rails applications are implemented using the Model-View-
Controller (MVC) architecture. Java developers are used to frameworks such
as Tapestry and Struts, which are based on MVC. But Rails takes MVC further:
when you develop in Rails, there’s a place for each piece of code, and all the
pieces of your application interact in a standard way. It’s as if you start out
with the skeleton of an application already prepared.
Professional programmers write tests. And again, Rails delivers. All Rails appli-
cations have testing support baked right in. As you add functionality to the
C HAPTER 1. I NTRODUCTION 15
code, Rails automatically creates test stubs for that functionality. The frame-
work makes it easy to test applications, and as a result Rails applications tend
to get tested.
Rails takes Ruby to the limit, extending it in novel ways that make a pro-
grammer’s life easier. This makes our programs shorter and more readable.
It also allows us to perform tasks that would normally be done in external
configuration files inside the codebase instead. This makes it far easier to see
what’s happening. The following code defines the model class for a project.
Don’t worry about the details for now. Instead, just think about how much
information is being expressed in a few lines of code.
class Project < ActiveRecord::Base
belongs_to :portfolio
has_one :project_manager
has_many :milestones
has_many :deliverables, :through => :milestones
Convention over configuration is crucial, too. It means that Rails has sensi-
ble defaults for just about every aspect of knitting together your application.
Follow the conventions, and you can write a Rails application using less code
than a typical Java web application uses in XML configuration. If you need to
override the conventions, Rails makes that easy, too.
Developers coming to Rails found something else, too. Rails is new, and the
core team of developers understands the new Web. Rails isn’t playing catch-
up with the new de facto web standards: it’s helping define them. And Rails
R AILS I S A GILE 16
makes it easy for developers to integrate features such as AJAX and RESTful
interfaces into their code: support is built in. (And if you’re not familar with
AJAX and REST interfaces, never fear—we’ll explain them later on.)
Developers are worried about deployment, too. They found that with Rails you
can deploy successive releases of your application to any number of servers
with a single command (and roll them back equally easily should the release
prove to be somewhat less than perfect).
The reason is both simple and subtle. Agility is part of the fabric of Rails.
Let’s look at the values expressed in the Agile Manifesto as a set of four pref-
erences.1 Agile development favors the following.
Rails is all about individuals and interactions. There are no heavy toolsets,
no complex configurations, and no elaborate processes. There are just small
groups of developers, their favorite editors, and chunks of Ruby code. This
leads to transparency; what the developers do is reflected immediately in what
the customer sees. It’s an intrinsically interactive process.
the heart of a Rails project. Instead, you’ll find a group of users and develop-
ers jointly exploring their need and the possible ways of answering that need.
You’ll find solutions that change as both the developers and users become
more experienced with the problems they’re trying to solve. You’ll find a frame-
work that delivers working software early in the development cycle. This soft-
ware may be rough around the edges, but it lets the users start to get a glimpse
of what you’ll be delivering.
That’s all tied to the idea of being able to respond to change. The strong, almost
obsessive, way that Rails honors the DRY principle means that changes to
Rails applications impact a lot less code than the same changes would in other
frameworks. And since Rails applications are written in Ruby, where concepts
can be expressed accurately and concisely, changes tend to be localized and
easy to write. The deep emphasis on both unit and functional testing, along
with support for test fixtures and stubs during testing, gives developers the
safety net they need when making those changes. With a good set of tests in
place, changes are less nerve-wracking.
Rather than constantly trying to tie Rails processes to the agile principles,
we’ve decided to let the framework speak for itself. As you read through the
tutorial chapters, try to imagine yourself developing web applications this way:
working alongside your customers and jointly determining priorities and solu-
tions to problems. Then, as you read the deeper reference material in the back,
see how the underlying structure of Rails can enable you to meet your cus-
tomers’ needs faster and with less ceremony.
One last point about agility and Rails: although it’s probably unprofessional
to mention this, think how much fun the coding will be.
The third part of the book, starting on page 229, is a detailed look at all the
functions and facilities of Rails. This is where you’ll go to find out how to
use the various Rails components and how to deploy your Rails applications
efficiently and safely.
Live Code
Most of the code snippets we show come from full-length, running exam-
ples, which you can download. To help you find your way, if a code listing
can be found in the download, there’ll be a bar above the snippet (just
like the one here).
Download work/demo1/app/controllers/say_controller.rb
This contains the path to the code within the download. If you’re reading
the PDF version of this book and your PDF viewer supports hyperlinks,
you can click the bar, and the code should appear in a browser window.
Some browsers (such as Safari) will mistakenly try to interpret some of
the templates as HTML. If this happens, view the source of the page to
see the real source code.
Ruby Tips
Although you need to know Ruby to write Rails applications, we realize
that many folks reading this book will be learning both Ruby and Rails
at the same time. Appendix A, on page 631, is a (very) brief introduction
to the Ruby language. When we use a Ruby-specific construct for the
first time, we’ll cross-reference it to that appendix. For example, this
paragraph contains a gratuitous use of :name, a Ruby symbol. In the :name
֒→ page 633
margin, you’ll see an indication that symbols are explained on page 633.
If you don’t know Ruby, or if you need a quick refresher, you might want
to go read Appendix A, on page 631, before you go too much further.
There’s a lot of code in this book....
David Says...
Every now and then you’ll come across a David Says... sidebar. Here’s
where David Heinemeier Hansson gives you the real scoop on some par-
ticular aspect of Rails—rationales, tricks, recommendations, and more.
Because he’s the fellow who invented Rails, these are the sections to read
if you want to become a Rails pro.
Joe Asks...
Joe, the mythical developer, sometimes pops up to ask questions about
stuff we talk about in the text. We answer these as we go along.
A CKNOWLEDGMENTS 19
This book isn’t a reference manual for Rails. We show most of the modules and
most of their methods, either by example or narratively in the text, but we don’t
have hundreds of pages of API listings. There’s a good reason for this—you get
that documentation whenever you install Rails, and it’s guaranteed to be more
up-to-date than the material in this book. If you install Rails using RubyGems
(which we recommend), simply start the gem documentation server (using the
command gem_server), and you can access all the Rails APIs by pointing your
browser at http://localhost:8808. (The sidebar on page 39 describes another way
of installing the full API documentation.)
Rails Versions
This book documents Rails 1.2.
If you are not running Rails 1.2, then you’ll need to update before trying the
code in this book. If Rails 1.2 is not yet available (this book went to print before
the official Gem was released), you can download an interim version. See the
instructions inside the front cover.
1.3 Acknowledgments
You’d think that producing a second edition of a book would be easy. After all,
you already have all the text. It’s just a tweak to some code here and a minor
wording change there, and you’re done. You’d think....
It’s difficult to tell exactly, but my impression is that creating this second
edition of Agile Web Development with Rails took about as much effort as the
first edition. Rails was constantly evolving and, as it did, so did this book.
Parts of the Depot application were rewritten three or four times, and all of
the narrative was updated. The emphasis on REST and the addition of the
deprecation mechanism all changed the structure of the book as what was
once hot became just lukewarm.
So, this book would not exist without a massive amount of help from the
Ruby and Rails communities. As with the original, this book was released as
a beta book: early versions were posted as PDFs, and people made comments
online. And comment they did: more than 1,200 suggestions and bug reports
were posted. The vast majority ended up being incorporated, making this book
immeasurably more useful than it would have been. Thank you all, both for
supporting the beta book program and for contributing so much valuable feed-
back.
As with the first edition, the Rails core team was incredibly helpful, answering
questions, checking out code fragments, and fixing bugs. A big thank you to
I’d like to thank the folks who contributed the specialized chapters to the
book: Leon Breedt, Mike Clark, James Duncan Davidson, Justin Gehtland,
and Andreas Schwarz.
I keep promising myself that each book will be the last, if for no other reason
than each takes me away from my family for months at a time. Once again:
Juliet, Zachary, and Henry—thank you for everything.
Dave Thomas
November 2006
dave@pragprog.com
Getting Started
Chapter 2
The model is responsible for maintaining the state of the application. Some-
times this state is transient, lasting for just a couple of interactions with the
user. Sometimes the state is permanent and will be stored outside the appli-
cation, often in a database.
A model is more than just data; it enforces all the business rules that apply
to that data. For example, if a discount shouldn’t be applied to orders of less
than $20, the model will enforce the constraint. This makes sense; by putting
the implementation of these business rules in the model, we make sure that
nothing else in the application can make our data invalid. The model acts as
both a gatekeeper and a data store.
$ # "
be a view that displays product information on a catalog page and another set
of views used by administrators to add and edit products.
MVC was originally intended for conventional GUI applications, where devel-
opers found the separation of concerns led to far less coupling, which in turn
made the code easier to write and maintain. Each concept or action was
expressed in just one well-known place. Using MVC was like constructing a
skyscraper with the girders already in place—it was a lot easier to hang the
rest of the pieces with a structure already there.
In the software world, we often ignore good ideas from the past as we rush
headlong to meet the future. When developers first started producing web
applications, they went back to writing monolithic programs that intermixed
presentation, database access, business logic, and event handling in one big
ball of code. But ideas from the past slowly crept back in, and folks started
experimenting with architectures for web applications that mirrored the 20-
year-old ideas in MVC. The results were frameworks such as WebObjects,
Struts, and JavaServer Faces. All are based (with varying degrees of fidelity)
on the ideas of MVC.
M ODELS , V IEWS , AND C ONTROLLERS 24
! Routing ! http://my.url/store/add_to_cart/123
" " Routing finds Store controller
# Controller interacts with model
$ Controller invokes view
Store %&View renders next browser screen
Controller
% $ #
Display Active
Cart Record Database
View Model
Ruby on Rails is an MVC framework, too. Rails enforces a structure for your
application—you develop models, views, and controllers as separate chunks of
functionality and it knits them all together as your program executes. One of
the joys of Rails is that this knitting process is based on the use of intelligent
defaults so that you typically don’t need to write any external configuration
metadata to make it all work. This is an example of the Rails philosophy of
favoring convention over configuration.
Figure 2.2, shows how Rails handles an incoming request. In this example, the
application has previously displayed a product catalog page and the user has
just clicked the Add To Cart button next to one of the products. This button
links to http://my.url/store/add_to_cart/123, where add_to_cart is an action in our
application and 123 is our internal id for the selected product.1
1. We cover the format of Rails URLs later in the book. However, it’s worth pointing out here that
having URLs perform actions such as add to cart can be dangerous. See Section 21.6, The Problem
with GET Requests, on page 463 for more details.
A CTIVE R ECORD : R AILS M ODEL S UPPOR T 25
The routing component receives the incoming request and immediately picks
it apart. In this simple case, it takes the first part of the path, store, as the
name of the controller and the second part, add_to_cart, as the name of an
action. The last part of the path, 123, is by convention extracted into an internal
parameter called id. As a result of all this analysis, the router knows it has to
invoke the add_to_cart method in the controller class StoreController (we’ll talk
about naming conventions on page 241).
The add_to_cart method handles user requests. In this case it finds the current
user’s shopping cart (which is an object managed by the model). It also asks
the model to find the information for product 123. It then tells the shopping
cart to add that product to itself. (See how the model is being used to keep
track of all the business data; the controller tells it what to do, and the model
knows how to do it.)
Now that the cart includes the new product, we can show it to the user. The
controller arranges things so that the view has access to the cart object from
the model, and it invokes the view code. In Rails, this invocation is often
implicit; again conventions help link a particular view with a given action.
Although it might not be immediately apparent from the SQL2 you use to
access them, relational databases are actually designed around mathematical
set theory. Although this is good from a conceptual point of view, it makes
it difficult to combine relational databases with object-oriented programming
2. SQL, referred to by some as Structured Query Language, is the language used to query and
update relational databases.
Another Random Document on
Scribd Without Any Related Topics
The Project Gutenberg eBook of Careers in
Atomic Energy
This ebook is for the use of anyone anywhere in the United States
and most other parts of the world at no cost and with almost no
restrictions whatsoever. You may copy it, give it away or re-use it
under the terms of the Project Gutenberg License included with this
ebook or online at www.gutenberg.org. If you are not located in the
United States, you will have to check the laws of the country where
you are located before using this eBook.
Language: English
Edward J. Brunenkant
by Loyce J. McIlhenny
CONTENTS
THE SCIENTIFIC MIND 3
COLLEGE: IS IT A NECESSITY? 5
PROFESSIONAL SATISFACTION 22
LOYCE J. McILHENNY
Engineering
Traditionally engineering has been somewhat different. Many
engineers held responsible jobs after receiving only a bachelor’s
degree. Some did earn a master’s degree, but few studied for a
doctorate.
In the last ten years, however, this trend has changed with
many more engineers receiving master’s and doctor’s degrees.
Advanced study is especially important for a career in the nuclear
field because the undergraduate years are filled mainly with basic
engineering, and most nuclear courses must be taken at the
graduate level. Moreover, the engineering sciences, as all other
fields, are becoming increasingly complex. Thus graduate study
through at least a master’s degree is advisable for the engineer.
The prospective engineering student should realize that a
bachelor’s degree will take from four to five years to complete, a
master’s degree will require an additional one to two years, and a
doctor’s degree will involve still another two to four years.
Medicine
A career in medicine is still a different story.
After three to four years in college premedical study, four years
in medical school, at least one year of internship, and possibly a
year’s medical residency, a doctor can become a general practitioner.
If he wishes to specialize, his internship may last for two years, and
his residency period from three to four years. It is this latter, longer
path that leads to a career in nuclear medicine and radiology, as well
as to more familiar specialization, such as surgery, pathology,
obstetrics, or pediatrics.
Veterinary Science
Also important in the field of nuclear medicine is the veterinary
scientist.
A veterinarian spends from two to four years in undergraduate
study and four years in veterinary school before receiving a Doctor
of Veterinary Medicine degree that permits him to practice animal
medicine. Then, if he wishes to enter nuclear veterinary medicine,
veterinary pathology, or some other specialty, he undergoes
additional training that is comparable to that of the physician who
specializes.
Scientific Writing
Valuable in all areas of science and engineering is the technical
writer.
Several years ago the typical technical writer or editor had a
background of journalism or English grammar and some
undergraduate study of one or more of the sciences. Editorial ability
still depends largely on ability to handle the English language, but
more and more frequently today the successful technical writer or
editor has a bachelor’s degree in one of the sciences. Sometimes he
has a master’s degree, and occasionally he holds a doctor’s degree.
Supporting Fields
No scientific organization can function if it is manned only by
scientists. Supporting and assisting personnel are essential to the
scientific team, and training is widely available for the nonscientist
who wants to work in a scientific installation.
Atomic energy, like fire, is not dangerous when it is under the
control of people who know how to use it. Special instruments and
protective clothing are used by trained technicians who are
responsible for radiation control.
Our website is not just a platform for buying books, but a bridge
connecting readers to the timeless values of culture and wisdom. With
an elegant, user-friendly interface and an intelligent search system,
we are committed to providing a quick and convenient shopping
experience. Additionally, our special promotions and home delivery
services ensure that you save time and fully enjoy the joy of reading.
ebookname.com