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.
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:
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:
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?
Here are the sketches of the pages. How do they fit in with the system requirements?
An application framework.
We need a set of pre-written code to that will form the foundation of the web application.
A database system.
We need some sort of database where we can store the data.
A web server.
We need somewhere to run the web application.
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.
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.
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.
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.
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.
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.
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.
Convention Over Configuration
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.
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.
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:
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
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?
Take a look in the db/migrate folder. You should see a file there called
<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:
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:
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 “...
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?
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?
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?
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
This is how the different types of code are connected in a Rails application:
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.
If we want to change the labels in web pages, we need to modify view code. And the view code all lives inside the
The view files generate web pages, and are called page templates. So what’s a page template, and what do those templates contain?
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.
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...
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?
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.
We need to CREATE code, but that doesn’t mean we need to WRITE code.
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:
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?
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:
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.
When we wanted to run a migration before we used the
But can we do that this time? After all, we don’t want
rake to run the first migration again by mistake.
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.
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:
You’ve got Chapter 1 under your belt, and now you’ve added the ability to create Rails applications to your toolbox.