Zero-to-Sixty: Creating and Deploying a Rails App in Under an Hour


Twice a month, we revisit some of our readers' favorite posts from throughout the history of Nettuts+. This tutorial was first published in January, 2010.

Give me an hour of your time, and I'll take you on a fly by of the Ruby on Rails framework. We'll create controllers, models, views, add admin logins, and deploy using Heroku's service in under an hour! In this article we'll create a simple bookshelf application where you can add books and write thoughts about them. Then we'll deploy the application in just a few minutes. So buckle up because this article moves fast!

This article assumes that you may know what Ruby on Rails is, but not exactly how it works. This article doesn't describe in-depth how each step works, but it does describe what we need to do, then the code to do that.


Ruby on Rails is a full stack MVC web application framework. Full stack means you get everything: a simple web server you can use to test your apps, a database layer, testing framework, and an MVC based design. MVC stands for Model-View-Controller.


A model stores information. Models are stored in the database. Rails supports MySQL, PostgreSQL, or SQLite. Each model has its own class and table. Say we want to model a "game." A game has things like number of players, a start time, end time, teams playing, and a winner. These attributes become columns in the "games" table. Table names are lowercase, underscored, and pluralized. The model's class name is Game. In Rails you create models through migrations and generators. A migration describes how to add/remove columns and tables from the database.


A controller is the manager. It takes information and does some logic like CRUD, or maybe import some stuff from a file, add/remove permissions--you name it a controller can do it. Controllers are the part of your app that does. How do we call controllers? Rails uses routes. A route is a formatted url that is tied to an action with a set of parameters. Going back to the Game model, we need a controller for functionality. At some point we'll to need to list all the games in the system. A basic REST url for this route looks like "/games" How does Rails know what controller to look for and what action to call? It looks at your routes.rb file. You may have a route that looks like this "GET /makes {:name => 'games', :action => 'index'"}. This translates to GamesController and it's index method. Just like models, class names are CamelCase and file names are underscored. So our GamesController would be stored in /app/controllers/games_controller.rb. After the logic, the controller renders a view.


A view is the easiest part to understand. It's what you see. It's the HTML you generate to show the user what they need. Views are ERB templates. ERB stands for Embedded Ruby. You use ERB similar to how you embed php into a document. If you want to insert an instance variable @game.time into some html write <%= @game.time %>


First install Rails. Installing Rails is very easy depending on your platform. If you are on a Linux/OSX, it's no problem. Windows is more complicated and I have no experience with it. This section will give you a brief overview of installing Rails through RubyGems, the Ruby package manager. A gem is a bundle of ruby code in a package that can be used in your programs. For UNIX based system, install RubyGems, then install the Rails gem. This process will go something like this:

Here are some links to help you through the setup process

Once you can run the "rails" command you're ready for the next step.


Now it's time to install database support before we get started. Rails has support for all the popular DB's, but for this example we'll use SQLite because it's lightweight.. Depending on your platform (again) installing sqlite support can be easy or painful. It can be a pain since the gem has to be built against C extensions, which means the sqlite3 package has to be installed on your system. Again the process will go something like this:

Read the previous links if you're having problems with these steps. They describe installing sqlite as well.


Time to generate our app. The rails command creates a base application structure. All we need to do is be in a directory and run it like so:

It's important to note that the Rails default is an SQLite based app. You may be thinking, what if I don't want that? The rails command is a generator. All it does is copy stored files into a new directory. By default it will create sqlite3 databases in /bookshelf/db/development.sqlite3, /bookshelf/db/production.sqlite3, and /bookshelf/db/testing.sqlite3. Database connection information is stored in /bookshelf/config/database.yml. You don't need to edit this file since it contains default information for an sqlite setup. It should look like this:

Notice there are different environments assigned. Rails has three modes: Development, Testing, and Production. Each has different settings and databases. Development is the default environment. At this point we can start our app to make sure it's working. You can see there's a directory called /script. This directory contains ruby scripts for interacting with our application. Some important ones are /script/console, and /script/server. We will use the /script/server command to start a simple server for our application.

Time to visit the application. Point your browser to "http://localhost:3000" and you should see this splash page:

Splash Screen

You're riding on Rails. Now that the code working on a basic level, it's time to delete the splash page and get started with some code.

Twenty Five

Our application needs data. Remember what this means? It means models. Great, but how we generate a model? Rails comes with some generators to common tasks. The generator is the file /script/generate. The generator will create our model.rb file along with a migration to add the table to the database. A migration file contains code to add/drop tables, or alter/add/remove columns from tables. Migrations are executed in sequence to create the tables. Run migrations (and various other commands) with "rake". Rake is a ruby code runner. Before we get any further, let's start by defining some basic information for the books. A book has these attributes:

  • Title : String
  • Thoughts : Text

That's enough to start the application. Start by generating a model with these fields using the model generator:

Open up the migration file:

Notice the create_table :books block. This is where columns are created. An id primary key is created automatically. t.timestamps adds columns for created_at and updated_at. Now, run the migration using the rake task db:migrate. db:migrate applies pending migrations:

Cool, now we have a table, let's create a dummy book just for kicks in the console. The Rails console uses IRB (interactive ruby) and loads all classes for your project. IE you can access to all your models. Open the console like this:

Now that we can create books, we need some way to show them to the user


Remember controllers? We need a controller to display all the books in the system. This scenario corresponds to the index action in our BooksController (books_controller.rb) which we don't have yet. Just like generating models, use a generator to create the controller:

We need to define an action that finds and displays all books. How did we find all the books? Earlier we used Book.all. Our strategy is use Book.all and assign it to an instance variable. Why an instance variable? We assign instance variables because views are rendered with the controllers binding. You're probably thinking bindings and instance variables...what's going on? Views have access to variables defined in actions but only instance variables. Why, because instance variables are scoped to the object and not the action. Let's see some code:

Now the controller can find all the books. But how do we tie this to a url? We have to create some routes. Rails comes with some handy functions for generating RESTful routes (another Rails design principle). This will generate urls like /makes and /makes/1 combined with HTTP verbs to determine what method to call in our controller. Use map.resources to create RESTful routes. Open up /config/routes.rb and change it to this:

Routes.rb can look arcane to new users. Luckily there is a way to decipher this mess. There is routes rake task to display all your routing information. Run that now and take a peek inside:

Now we need to create a template to display all our books. Create a new file called /app/views/books/index.html.erb and paste this:

This simple view loops over all @books and displays some HTML for each book. Notice a subtle difference. <%= is used when we need to output some text. <% is used when we aren't. If you don't follow this rule, you'll get an exception. Also notice the h before book.title. h is a method that escapes HTML entities. If you're not familiar with ruby, you can leave off ()'s on method calls if they're not needed. h text translates to: h(text).

Time to run the server and see what we've got. Start the server, then go to http://localhost/books.

If all goes according to plan you should see some basic HTML.


Thirty Five

We have one book in our system, but we need some more books to play with. There are a few ways to go about doing this. I like the forgery gem. Forgery can create random strings like names, or lorem ipsum stuff. We are going to set a gem dependency in our app, install the gem, then use it to create a rake task to populate our data. Step 1: open up /config/environment.rb and add this line:

Now we're going to use the Forgery classes to create some fake data. The Forgery documentation is here. We'll use the LoremIpsumForgery to create some basic data. We can define our own rake tasks by creating a .rake file in /lib/tasks. So create a new file /lib/tasks/populate.rake:

This rake task will create five fake books. Notice I added a begin/rescue. When you run a rake task it looks at all possible tasks in the rake initialization. If you were to run any rake task before you installed the gem, rake would blow up. Wrapping it in an begin/rescue stop rake from aborting. Run the task to populate our db:

Start the server again and head back to the /books pages. You should see:

Book Index

Now we have a listing of more than one book. What if we have a lot of books? We need to paginate the results. There's another gem for this. The gem is 'will_paginate.' Following the same steps as before, let's add a gem dependency for 'will_paginate' and rake gems:install:

Head back to your /books page and you should be bombarded by books at this point. It's time to add pagination. Pagination works at two levels. The controller decides which books should be in @books, and the view should display the pagination links. The will_paginate helper makes this very easy. We'll use the .paginate method and the will_paginate view helper to render page links. All it takes is two lines of code.

Head back to your /makes page and you should see some pagination links (given you have more than 10 books)

Paginated Books

Sweet! We are movin' through this app. It's time to spruce up our page a little bit. One key Rails principle is DRY (Do Not Repeat Yourself). We could work through the exercise of doing some basic CSS to get a page looking OK, or we could keep things DRY and use some code to do it for us. We are going to use Ryan Bate's nifty-generators gem to generate a layout for the site. A layout is a template your views can fill in. For example we can use a layout to determine the over all structure of a page, then define where the views fill it in. Since this isn't a project dependency, we don't have to add it to environment.rb. We can just install it regularly.

Run the generator to create a layout file and stylesheets.

Take a look at the application.html.erb file and see what's inside:

See those yields? That's where a view fills in the layout. The last yield has no argument. Default content goes there. Yields with an argument must have content defined using content_for. Fix up index.html.erb view to go with the new layout:

All we did was add the title method which sets the title for a page. The title helper calls content_for :title and sets it to the argument. Our view fills in the last yield. Check out the results!

Nifty Layout


Now that our application is looking better, let's add some interaction. In typical Web 2.0 style we're going to allow users to comment on our content, but we aren't going to require the user to register. We need to create new model called Comment. A comment is going to have some text, an author, and an associated Book. How do we link these two models together? Associations. Rails provides these associations: belongs_to, has_many, has_one, and has_and_belongs_to many. It should be easy to see that a book has many comments, and a comment belongs_to a book. So we'll use a generator to create the comment model and migration:

Astute readers will notice that this migration is lacking the foreign key column. We'll have to add that ourselves. Open up your create_comments.rb migration:

Now it's time to associate our models using the Rails associations. We'll call the method inside the model's class body. Rails uses metaprogramming to generate the methods needed to make our association work. We'll edit our comment.rb and book.rb files:

Now Book instances have a method .comments with returns an array of all its comments. Comment instances have a method called .book that return the associated book. Use the << operator to add objects to arrays. Let's see how it works in the console:

In the console session I found one of the existing books, then created a new comment. Next I added it to the book.comments. Then I save book. The book must be saved for the association to be stored. What's next? We need to create a page where the user can view a book and all it comments. That page should also have a form where the user can add their comment. Create a new action in the books controller to show the details for a specified book. The book is found by id. Pop into books_controller.rb and add this:

Make a new template for this action at /app/views/books/show.html.erb and paste this:

Now let's add some links for the index actions to link the show action:

Remember our url helpers from rake routes? We're using book_path to generate a url to the book controller's show actions. If you don't remember check rake routes again. link_to is a helper to generate a link tag. Now let's fire up our server and click through the app. Now you should have some ugly blue links. Click on your book title and it should go to /books/:id aka BooksController#show:


Time to display some comments. Remember that console session we did a little bit back? One of our books has some comments. let's update our controller to find the comments and our show.html.erb to display them.

So we assign @comments in the controller to be all the book's comments, then do a loop in the view to display them. Head over to /books/1 (1 came from Book.find(1) in the console session). Check this out:


Now we need the form to create a new comment. We need two things. 1, A comments controller to save the comment, and 2 a route to that action. let's tackle #1 first.

Create action that instantiates a new comment, sets its attributes (text/author) from the submitted form data, and saves it.

First the code finds the book, then creates a new comment form the form data, saves it, sets a message, then redirects back to that book's page. params holds a hash of all GET/POST data with a request. Now we need to create a route to the controller's action. Open up routes.rb:

Head back to the /books page and make sure nothing has blown up. Everything should be fine and dandy. Now for constructing the form. We need a form that submits POST data to /book/:book_id/comments. Luckily Rails has the perfect helper for this: form_for. form_for takes some models and generates a route for them. We pass form_for a block to create form inputs. Go ahead and paste this into the bottom of your show.html.erb:

We call form_for to create a new form for the book's comment, then use the text_field/text_area to create inputs for attributes. At this point we can go ahead and make a comment. Fill in the form and viola you now have comments!

We can comment!

See that green thing? That's the flash. The flash is a way to store messages between actions. It's perfect for storing little messages like this. But what do we do if a book has too many comments? We paginate them just like did before. So let's make some changes to the controller and view:

Start commenting on your books and you should see some pagination.

Paginated Comments

Now people can comment, and everything is paginated but we're missing something. We have no web interface for creating books. We need to create a form for that. Also we are the admin so only I should be allowed to create books. This means we need to create a user, login, and check to see if they can do an action.


Now we're going to implement CRUD functionality for admins. First we'll implement actions to create, edit, and delete books. Then we'll create an admin login. Finally we'll make sure only admins can do those actions.

Creating a new books requires two new actions. One action that renders a form for a new book. This action is named 'new'. The second is named 'create.' This action takes the form parameters and saves them in the database. Open up your books_controller.rb and add these actions:

We also need a new view that shows a form. Create a new file /apps/views/books/new.html.erb and paste this:

Now we're ready to create a new book. Point your browser to /books/new and you should see this form. Go a head and create a new book. After you fill in your form you should see your new book.

New Book Form
Saved book

Get rid of the double header in /app/views/books/show.html.erb and add some links to actions an admin can do on that book. Open up that file and set it's contents to:

Head over to a book's page and you should see:

Updated book's page

Now that we have some links to edit and delete, you can implement them. Editing a book works just about the same as creating a new one. We need an action that shows an edit form, and one to save the changes. Delete is just one action that deletes the record from the database. Open up books_controller.rb and add these actions:

The edit action finds the requested book from the id in the url. The update action finds the book from the id and uses the update_attributes method to set the new values from the form. Delete finds the book by id and deletes it. Then it redirects you back to the books listing.

Next we have to create an edit form. This form is exactly the same as the create form. We can just about duplicate the show.html.erb to edit.html.erb. All we are going to do is change the title. Create a new file in /app/views/books/edit.html.erb and paste this:

Now from one of the book's pages, click the edit link. You should see a familiar form:

Editing a book

Notice how Rails filled in the inputs with the saved values? Nice huh. Go ahead and save some changes to a book. When you're done you should see this:

Viewing an edited book.

Now delete that book. You should get a confirmation dialog then be redirected back to /books.

Are you sure? Book deleted.

Add a link to create a new book on the index page. Open up /app/views/books/index.html.erb and add this to the bottom:

Now that we have CRUD functionality. We need to create our admin user.

Fifty Five

Maintaing user logins is a solved problem in Rails. You rarely have to write your own authentication system. We're going to use the authlogic gem. Authlogic provides simple mechanics to authenticate users and store sessions. This is prefect for our app. We need an admin to login so he can create/edit/delete books. First let's start by installing the authlogic gem.

Create a new model to hold the admins. Since our users are only admins, we'll name the model Admin. For now the model only needs a login attribute. Generate the model using script/generate model:

Now add authlogic specific columns to our admin model. Open up the migration you just created and paste this into it:

Now migrate your database.

Now the admin model is created. Next we need to create an authlogic session for that admin. Authlogic includes a generator for this:

Next we need to create some routes for logging in and out. Open up routes.rb and add this line:

Now we need a controller to handle the logging in and out. Generate this controller using the generator:

Now open up /app/controllers/admin_sessions_controller.rb and paste this into it:

Wow! It seems like we just did a lot, but we haven't. We've just created 2 new models. One model to hold our admins, and the other to hold admin session information. Finally we created a controller to handle the logging in and out. Now we need a view to show a login form. Create a new file at /app/views/admin_sessions/new.html.erb and paste this into it:

We're almost done. We still need to tell our Admin model that it uses authlogic and add some logic to our application controller to maintain session information. All controller inherit from application_controller, so it's a good way to share methods between controllers. Open up /app/controllers/application_controller.rb and paste this:

Now in /app/models/admin.rb add this line inside the class:

We're finally ready to do some logging in and out. All of the stuff we did was almost purely from the authlogic documentation examples. This is a standard setup for many applications. If you want to find out more about how authlogic works you can here. Here's a run down of what we did.

  1. Install the authlogic gem
  2. Create an Admin model to hold the basic information like login/password
  3. Add authlogic specific columns to the Admin table
  4. Generated an authlogic admin session
  5. Created routes for logging in and out
  6. Generated an AdminSession controller to do all the work
  7. Created a view that shows a login form
  8. Added methods to ApplicationController for persisting sessions
  9. Told the Admin model that it uses authlogic

It's time to create the admin account. Our application is simple and only has one admin. Since we only have one admin, we can easily use the console. Since we'll need to recreate that user later when we deploy, it doesn't make sense to do the same thing twice. Rails now has a functionality for seeding the database. This is perfect for creating the initial records. There is a file /db/seeds.rb where you can write ruby code to create your initial models. Then you can run this file through rake db:seed. In order to create our admin model we'll need a login, password, and password confirmation. Open up /db/seeds.rb and paste this. Fill in the login with the name you want.

We use the create! method because it will throw an exception if the record can't be saved. Go ahead and run the rake task to seed the database:

Now we should be able to login. Restart the server to get the new routes. Head to /admin_session/new. You should see:

Login Form

Go ahead and fill it in and now you should be logged in!

ZOMG logged in!

Now that admins can login, we can give them access to the new/edit/delete functionality. Rails has these awesome things called filters. Filters are things you can do at points in the request lifecycle. The most popular filter is a before_filter. This filter gets executed before an action in the controller. We can create a before filter in the books controller that checks to see if we have a logged in admin. The filter will redirect users who aren't logged in, therefore preventing unauthorized access. Open up books_controller.rb and add these lines:

Now we need to update our views to show the admin links only if there's an admin logged in. That's easy enough. All we need to do is wrap it in an if.

We still need to add a login/logout link. That should go on every page. An easy way to put something on every page is add it to the layout.

Now you should have login/logout links on pages depending if your logged in and logged out. Go ahead and click the through the app. Try access the new book page after you've logged out. You should see an error message.

Access Denied

Click through the app. You should be able to login and out, and edit/create/delete books. Time for the final step. Let's add some formatting to your thoughts and user comments. Rails has a helper method that will change new lines to line breaks and that sorta thing. Add that show.html.erb:

It doesn't make sense to put the thoughts in the index, so let's replace that with a preview instead of the entire text.

Now our final index page should look like this:

Easier index.

Finally we need to set up a route for our root page. Open up routes.rb and add this line:

Now when you go to / you'll see the book listing.


Now we are going to deploy this app in a few steps. You don't need your own server or anything like that. All you need is an account on Heroku. Heroku is a cloud Rails hosting service. If you have a small app, you can use their service for free. Once you've signed up for an account, install the heroku gem:

Heroku works with git. Git is a distributed source control management system. In order to deploy to heroku all you need to do is create your app then push your code to it's server. If you haven't already install git, instructions can be found here. Once you have heroku and git installed you are ready to deploy. First thing we need to do is create a new git repo out of your project:

It's time to do some preparation for heroku deployment. In order to get your application's gems installed, create a .gems file in the root project directory. Each line has the name of the gem on it. When you push your code to heroku it will read the .gems file and install the gems for you. So create a .gems file and paste this into it:

There is a problem with authlogic on heroku, so we need to create an initializer to require the gem for us. Create a new file in /config/initializers/authlogic.rb and put this line in there:

Now we should be ready to deploy. First thing you're going to do is run heroku create. This will create a new heroku app for you. If you're a first time user, it will guide you through the setup process.

No we are ready to deploy. Here are the steps

  1. Add all files in the project to a commit
  2. Commit the files
  3. Push are code to heroku
  4. Migrate the database on heroku
  5. Seed the database on heroku
  6. Restart the heroku server
  7. Open your running application

Here is the finally app running on the world wide web:


Hit the Brakes

We've covered a lot of ground in this article, so where do we go from here? There are few things we didn't do in this app. We didn't add any validations to the models. We didn't use partials. We didn't do any administration for the comments. These are things you should look into next. Here are some links to help you with the next steps.

  • Completed Source Code
  • Confused about the form parts? Read this
  • Confused about routes? Read this
  • Confused about heroku? Read this
  • Confused about associations? Read this
  • Confused about authlogic? Read this

Links to gems used in this project.

Ready to take your skills to the next level, and start profiting from your scripts and components? Check out our sister marketplace, CodeCanyon.


Write a Plus Tutorial

Did you know that you can earn up to $600 for writing a PLUS tutorial and/or screencast for us? We're looking for in depth and well-written tutorials on HTML, CSS, PHP, and JavaScript. If you're of the ability, please contact Jeffrey at

Please note that actual compensation will be dependent upon the quality of the final tutorial and screencast.

Write a PLUS tutorial