ChapterÂ 1.Â Getting Started: Really Rapid Rails
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:
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?
The application needs to do lots of things
Here are the sketches of the pages. How do they fit in with the system requirements?
So what things do we need for the app?
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.
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
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
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.
So what does this do?
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.
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.
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 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:
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
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?
Create the table by running a migration
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 â...
Sweet! You saved your buddyâs job!
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?
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
The 3 parts of your app: model, view, and controller
This is how the different types of code are connected in a Rails application:
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.
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
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
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...
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?
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.
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:
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:
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.
You need to run your migration with rake
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.
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.
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:
The concert is a sell-out!
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.