O'Reilly logo

Head First Rails by David Griffiths

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

Chapter 1. Getting Started: Really Rapid Rails

image with no caption

Want to get your web app development off to a flying start? Then you need to know Rails. Rails is the coolest and quickest development framework in town, allowing you to develop fully functional web apps quicker than you ever thought possible. Getting started is simple; all you need to do is install Rails, and start turning the pages. Before you know it, you’ll be miles ahead of the competition.

Friday, 9 AM

The first email you open is from an old friend in trouble:

Hey - how you doing?

I need a *big* favor! Remember that ticket-sales application I said we were working on? It’s not going well. We’ve been working on it for weeks! The team is having real problems.

Do you think you could create the application for us?

We need a web site that can:

  • List all sold tickets

  • Create a new ticket sale

  • Read and display a single ticket

  • Update the details of a sale

  • Delete a ticket sale

I know that seems like a lot of functions, but the boss says that it’s the minimum set of features they need - and you know he’s a tough guy to argue with! Here’s the data structure:

Ticket:

  • name - name of purchaser (string)

  • seat_id_seq - the seat number e.g. E14 (string)

  • address - address of purchaser (long string)

  • price_paid - sales price of ticket (decimal)

  • email_address - email of purchaser (string)

I’ve attached sketches of the pages too so you know what we’re aiming at. Oh - and we need all of this for Monday or my butt’s on the line. Help!

The system is designed to be used by front-of-house staff in the concert arena. The database will be reset for each concert, so it will only need to record the details for one concert at a time. Think you can help?

The application needs to do lots of things

Here are the sketches of the pages. How do they fit in with the system requirements?

image with no caption

Brain Power

What types of software will you need to build and run the application?

So what things do we need for the app?

There are several things we need to run the application on the arena’s server. We need:

  1. An application framework.

    We need a set of pre-written code to that will form the foundation of the web application.

  2. A database system.

    We need some sort of database where we can store the data.

  3. A web server.

    We need somewhere to run the web application.

  4. An object-relational mapping library.

    To simplify access to the database, most web applications now use an O-R mapping library to convert the database records into objects.

    image with no caption

So how does Rails help us?

Regardless of what language you code in, you will probably still need these three things for your deployed application. One of the great things about Rails is that it contains all of the software you will need—all bundled in for free.

Let’s see how this works.

Rails is for database-centric apps like the ticket sales system

A lot of applications have a database at the heart of them. The main reason these application exists is so that users can access and modify the contents of the database without using SQL directly.

So what are the problems that need to be solved when you connect a database to a web application?

Well, the web application will need to allow the user to access and modify data, so Rails includes an application framework called the ActionPack that will help you generate data-driven, interactive pages.

Secondly, web applications need to be run on a web server to display these pages, so Rails comes with one built in.

Thirdly, you need a database. Rails creates applications that are configured to work with an integrated SQLite3 database.

The fourth thing you need is an object-relational mapping library and Rails provides one called ActiveRecord. This makes your database look like a collection of simple Ruby objects.

As well as all this, Rails also includes a pile of tool scripts to help you manage the application. So if you are creating a database-centric web application you’ll find that

Rails gives you everything you need.

You create a new application with the rails command

So how do you get started with Rails?

Creating a new web application is actually really simple in Rails. All you need to do is open up a command prompt or terminal window, and type in rails tickets, where tickets is the name of the application you want to create.

Do this!

image with no caption

So what does this do?

Typing rails tickets cleverly generates a web application in a new folder called “tickets”. Not only that, within the tickets folder, Rails generates a whole host of other folders and files that form the basic structure of a new application.

This means that you’ve effectively created an entire basic web application with just one short command.

image with no caption

Relax

Rails generates a lot of files and folders, but don’t worry.

They’re all there for a reason, and you’ll understand what they all do by the end of the book.

Geek Bits

Rails starts its web server on port 3000 by default. It you want to use another port, such as 8000, run

ruby script/server -p 8000

Now you need to add your own code to the default app

Rails creates the basic structure of your app from the get-go, but you still need to add the code that is specific to what you want. Everybody’s application is different, but does Rails have any tools or tricks that make it easier for you to create custom code?

Well, actually, it does. Did you notice how Rails created a whole file structure for you, almost as if it knew what you were going to need? That’s because Rails apps follow very strong naming conventions.

Rails principle:

Convention Over Configuration

Rails apps always follow conventions

All Rails applications follow the same basic file structure and use consistent names for things. This makes the application easier to understand, but it also means that the built-in Rails tools will understand how your application works.

So why is that important? Well if the tools know how your app is structured, you can use them to automate a lot of the coding tasks. That way, Rails can use conventions to generate code for you, without you having to configure your web application. In other words, Rails follows convention over configuration.

Let’s look at one of Rails most powerful tools: scaffolding.

Scaffolding is GENERATED code

So what does our application need to do? Let’s look at that email again:

image with no caption

So we need to create web pages that allow us to Create, Read, Update, and Delete tickets. Because the initial letters of the operations are C, R, U, and D, they are known as the CRUD operations. These are pretty common operations in database-centric applications—so common that Rails has a way of quickly generating all the code and pages you need. It does all this using scaffolding.

So what does the scaffold command do?

Scaffolding creates code that allows a user to create, read, update, and delete data in the database.

If you have a database-centric web application that needs to create, read, update, and delete data from a database, then scaffolding can save you lots of time and effort.

Type the scaffold command for the ticket table into the console, and let’s see what happens:

Do this!

image with no caption

Brain Power

Think about the error message you can see in the web browser. Why do you think the application crashed?

There are no tables in the database yet!

The application should have displayed an empty list of sold tickets, but it didn’t. Why not? It needed to read the list from table called tickets in the database, but we haven’t created any tables yet.

Should we just connect to the database and create the table? After all—the database is sitting right there in the application. But then, why should we have to? We already told Rails enough information for Rails to create the table for us. Look again at our scaffold command:

image with no caption

We already told Rails the details of the data structure when we ran the scaffold command, and there is an important principle in Rails: Don’t Repeat Yourself. If you tell Rails something once, you shouldn’t have to say it again.

So how do we get Rails to create the table?

image with no caption

Geek Bits

Rails comes bundled with a database, SQLite3. So where is it?

The database is located within the db folder, in the file development.sqlite3.

Create the table by running a migration

When Rails generated the scaffolding, it also generated a small Ruby script called a migration to create the table. A migration is a script that alters the structure of the underlying database.

Take a look in the db/migrate folder. You should see a file there called <timestamp>_create_tickets.rb where <timestamp> is the UTC timestamp of when the file was created. If you open the file in a text editor, it should look something like this:

image with no caption

The migration is a small Ruby script. Instead of running this script directly, you should run this script using another Rails tool called rake. To run the migration, type rake db:migrate at the command prompt. This runs the migration code and creates the table:

image with no caption

Watch it!

Rails uses CamelCase for classes but under_scores for filenames.

Don’t worry, we’ll talk more about this later.

That’s why the migration is called “CreateTickets” and it lives in a file called “... _create_tickets.rb

Brain Barbell

Why does the migration include the date and time in its name?

Sweet! You saved your buddy’s job!

Your quick Rails work saved the day for your pal... at least, for the moment. Looks like there’s another email to deal with:

Thank you!

It’s great to see the application up and running - and you did it so quickly! Rails sounds amazing. The way changes appear as soon as you edit the code. No compile. No deploy. Must be nice.

You really saved my butt on this one.

Just one thing - the labels for seat_id_seq should be something more human-readable, like maybe “Seat #”. Do you think you could fix that?

So how can we change the labels?

Rails generated a web app for us very quickly, which saved us a lot of time and effort. But what if we want to make small changes to the appearance of the generated pages, what do we do?

How easy is it to modify the pages that Rails has generated for us?

To modify an app, you need to dig into the app’s architecture

Scaffolding just generates code for us. Once the code’s been generated, it’s up to you to customize that code. And if you look in the app folder, you’ll see there’s quite a lot of generated code you might want to customize.

So if you need to make a change to the application—like modifying the page labels—where do you begin?

image with no caption

Rely on Rail’s conventions.

Remember how we said that Rails apps follow conventions over configuration? This will make it easier for us to modify the application. Why? Well, because the code is separated according to it’s function. That means Ruby scripts that do similar things live in similar places.

So if you need to change the behavior of your Rails application, you should be able to identify where the code is that needs to be amended, and change the code.

But of course to do that, you need to understand the...

Standard Rails Architecture

image with no caption

The 3 parts of your app: model, view, and controller

Pretty much all of the code in a Rails application falls into one of three categories:

  1. Model Code

    The model code manages how data is written and read to your database. Model code objects represent things that exist in the system’s problem domain—like the tickets in the ticket system

    Note

    This just means the business problems your app’s trying to solve.

  1. View Code

    The view is the part of the application that is presented to the user. For that reason it is sometimes called the presentation layer. For a web application, the view mostly generates web pages.

  1. Controller Code

    The controller is the real brain of the application. It decides how the user interacts with the system, controlling what data is accessed from the model, and which parts of the view will present it.

This is how the different types of code are connected in a Rails application:

image with no caption

The 3 types of code are kept in SEPARATE folders

So Rails favors convention over configuration and uses the MVC architecture. So what?

How does the MVC architecture help us change the labels on our pages and fix the app? Let’s look back at the files that were generated by the scaffolding one more time. Because the code is cleanly separated into three distinct types—model, view, and controller—Rails puts each type in a separate folder.

image with no caption

The files in the VIEW need to be edited

If we want to change the labels in web pages, we need to modify view code. And the view code all lives inside the app/views folder.

The view files generate web pages, and are called page templates. So what’s a page template, and what do those templates contain?

Edit the HTML in the view

So what do the page templates actually look like? Open the four .html.erb files in the views/tickets folder using a text editor. The contents of the files look an awful lot like HTML.

We want to change the labels for seat_id_seq to Seat #. To do this, search for the text “Seat id seq” in the four files, change it to “Seat #”, and then save your changes.

image with no caption

If you edit the labels in your HTML, your changes become immediately visible in your web browser. If you make the changes now and refresh, they should be visible immediately. Let’s take a look next...

Do this!

Go into each of the four .html.erb files in the views/tickets folder, and change the text Seat id seq to Seat #. This will change the label on the pages to Seat #.

Sunday, 8 AM

Two fixes down, but your phone’s ringing... what now?

image with no caption
image with no caption

The application needs to store more information now

Everything was pretty much finished until your friend mentioned that phone numbers need to be recorded. We need more data, so what’s that mean for our app?

  1. We need an extra field displayed on each page.

    Fortunately we know how to amend page templates, so this shouldn’t be too big of a problem.

    image with no caption
  2. We need to store an extra column on the database.

    We need to store an extra column in our database, but how?

    image with no caption

A migration is just a Ruby script

So we need a migration to add a column to the table. But what is a migration, really? Let’s look back at the one that created our tickets table.

class CreateTickets < ActiveRecord::Migration
  def self.up
    create_table :tickets do |t|
      t.string :name
      t.string :seat_id_seq
      t.text :address
      t.decimal :price_paid
      t.string :email_address
      t.timestamps
    end
  end
  def self.down
    drop_table :tickets
  end
end

We need to create code that’s something like this, except instead of creating a table, we need our migration to add a column.

image with no caption

We need to CREATE code, but that doesn’t mean we need to WRITE code.

Rails can generate migrations

Remember when we generated the scaffolding using:

ruby script/generate scaffold ticket name:string seat_id_seq:string
address:text price_paid:decimal email_address:string

generate is a script to create Ruby code. And the good news is that generate doesn’t just write scaffolding code. It can also generate migrations.

Now suppose you were to type in this command:

image with no caption

This would generate a brand new blank migration file. We could then add in the Ruby code to modify the table. The trouble is, we don’t know how to write the code to complete the migration.

So what can we do? And what can Rails do for us?

Give your migration a “smart” name, and Rails writes your code for you

You’ve probably noticed by now that names are really important to Rails. When we created scaffolding called “ticket,” Rails made the app visible at http://localhost:3000/tickets and generated a migration to create a table called tickets.

Naming conventions are important in Rails because they save you work. The same is true with how you name migrations. Instead of just giving the new migration any old name, try giving it a name like this:

image with no caption

So why does the name make any difference?

Rails knows that a migration called Add...To... is probably going to be adding a particular column to a particular table, so instead of just generating a blank migration for you to fill in, Rails will actually write your migration code for you.

image with no caption

You need to run your migration with rake

Here’s the migration that Rails cleverly generates for you.

image with no caption

When we wanted to run a migration before we used the rake command:

rake db:migrate

But can we do that this time? After all, we don’t want rake to run the first migration again by mistake.

Timestamps tell rake which migrations to run, and in which order

Rails records the latest timestamp of all the migrations it runs. That allows rake to tell which migrations have been run and which haven’t. This means that whenever you run rake db:migrate, Rails will only run the latest migrations.

Let’s put this to the test. Run rake db:migrate again to add the phone column to the tickets table.

Do this!

image with no caption

But changing the database isn’t enough

Scaffolding generates code—and that’s great because it gets you up and running very quickly. But the downside is that once the code has been generated it the developer’s responsibility to keep the code up-to-date.

We just added a phone attribute to the database. But because the forms had already been created by scaffolding, they won’t automatically pick-up the new phone field. So we’ll have to go back to the page templates and add in references to the phone number:

image with no caption
image with no caption

The concert is a sell-out!

The application runs perfectly all week, and the following Friday night, every seat in the arena is sold.

image with no caption
image with no caption

Tools for your Rails Toolbox

You’ve got Chapter 1 under your belt, and now you’ve added the ability to create Rails applications to your toolbox.

Rails Tools

rails app-name

  • Create an application

ruby script/server

  • Start the application

ruby script/generate scaffold...

  • Generate CRUD code for a model

ruby script/generate migration

  • Generate a migration to alter the database structure

rake db:migrate

  • Run new migrations on the database

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required