- A working version of Rails 4.0. To determine if you’ve got a working version of Rails 4.0, type
rails -vinto your command prompt, or ask a mentor.
- Sublime Text. If you prefer another text editor like Vim, emacs, TextMate or Github’s Atom that’s fine too but these instructions will specifically mention Sublime.
Open two command prompts.
To do this on Windows: Open the Command Prompt window by clicking the Start button, clicking All Programs, clicking Accessories, and then clicking Command Prompt.
To do this on Mac: Open Finder in the Dock. Select applications. Then choose utilities. Double click on Terminal.
You’ll use one of the command prompts to run your local Rails server and the other for entering all other commands.
Whenever you need to start or restart the rails server use the first command prompt and for all other command line work you can use the second command prompt.
Setting up our Rails app
rails new quick_blog -T
Entering this command into your command prompt will cause Rails to generate a new application and begin to install dependencies for your application. This process may take a few minutes, so you should let it continue. The
-T is short for
--skip-test-unit. We won’t be specifically covering testing just now, so we won’t need the
test directory that Rails normally provides for you when generating a new project.
If you have installed multiple versions of Rails onto your computer, you can choose which one to create an app with as follows:
rails 3.2.13 new quick_blog -T
Once it has finished type:
Entering this command will change you into the folder where your application is stored. If you look at the contents of this folder you’ll see:
This is the standard structure of a new Rails application. Once you learn this structure it makes working with Rails easier since everything is in a standard place.
Now run the following command:
This checks the gems in your gemfile and will fetch all remote sources, resolve dependencies and install all required gems. (a gem is just a small program that you add to your application to provide out-of-the-box funtionality).
It may take a while to run so sit back and relax…
Next we’ll run this fresh application to check that our Rails install is working properly. Type:
Open your web-browser and head to: http://localhost:3000 you should see something that looks like:
Now that you’ve created the Rails application you should open this folder using Sublime. Open up Sublime, then open the quick_blog folder that was just generated.
Creating basic functionality
Now we’re ready to get started building an actual blog. In your command prompt
Ctrl-c to stop the Rails server, or use your second command prompt and navigate to your Rails application folder. Then you can use a Rails generator
to build some code for you:
rails generate scaffold Post title:string body:text
Let’s break this command down: we’re asking
(basic building blocks; think construction scaffolding) for a thing,
or in Rails parlance a “resource”, we want to call a
Post in our system.
We want to give our
Post two attributes: a
title, which we want to be a
string, and a
body, which we want to be
string is computer-speak for a short sequence of characters like
"Are you having fun, yet?", and can usually be as long as your average tweet.
Blog titles tend to be short, so we’ll use a
string for ours.
text is like a
string, but longer, so we’ll use it to have enough room to write as many
paragraphs as we want in the
body of our blog post.
After running your command, you’ll be presented with something that looks like:
An important file that was generated was the migration file:
db/migrate/20140528075017_create_posts.rb Note that as this file name starts
with a unique id including the date and time yours will have a different set
class CreatePosts < ActiveRecord::Migration def change create_table :posts do |t| t.string :title t.text :body t.timestamps end end end
This file is Ruby code that Rails uses to manage how your data is stored in the
database. You can see that this code is to create a table called
Posts and to
create two columns in this table, a title column and a body column. Finally we
need to instruct Rails to apply this to our database. Type:
Once this command has run you can start up your Rails server again with
server and then navigate to
http://localhost:3000/posts to see the changes
you’ve made to your application.
From here you can play around with your application. Go ahead and create a new blog post.
You’ll notice you can create new posts, edit or delete them. We’re going to add
in some functionality to our new Rails app which enforces a rule that every
post must have a title. Open
app/models/post.rb in Sublime and add the line:
validates_presence_of :body, :title
To the code. Your
post.rb file should look like:
class Post < ActiveRecord::Base validates_presence_of :body, :title end
We can check that this works by editing our blog post, deleting the title and
Update Post. You’ll get an error informing you that you’ve just
attempted to break the rule you just inserted:
Making things prettier
Right now our show post page isn’t looking
very good. We’ll open
app/views/posts/show.html.erb in Sublime and make it look like the
<p id="notice"><%= notice %></p> <h2><%= link_to_unless_current @post.title, @post %></h2> <%= simple_format @post.body %> <%= link_to 'Edit', edit_post_path(@post) %> | <%= link_to 'Back', posts_path %>
At this point you can refresh the show post page in your browser to see the changes you’ve made.
We’ll also want to make our blog listing prettier too, we’ll use a Rails
partial (a partial is simply a reusuable block of HTML code. It’s part of a web
page) to achieve this. We want our listing and the individual blog pages to
look the same so first we’ll create a file:
The underscore in front of the filename here tells Rails that this is a
partial. We’ll take
<h2><%= link_to_unless_current @post.title, @post %></h2> <%= simple_format @post.body %>
app/views/posts/show.html.erb and put it in our
After that, change all three mentions of
@post to be
post instead. This
_post.html.erb file will be:
<h2><%= link_to_unless_current post.title, post %></h2> <%= simple_format post.body %>
show.html.erb file we want to insert the code to put our partial into
our show view. Insert the code:
<%= render partial: @post %> to make it
<p id="notice"><%= notice %></p> <%= render partial: @post %> <%= link_to 'Edit', edit_post_path(@post) %> | <%= link_to 'Back', posts_path %>
Save all these files and refresh the show posts page. This is to check that you haven’t broken anything with those changes.
Our index page still hasn’t changed, so we’re going to open the
index.html.erb file up and remove the table in there and replace it with the
partial again so we’re re-using that code:
<h1>Listing posts</h1> <%= render partial: @posts %> <%= link_to 'New Post', new_post_path %>
One huge problem with our blog is that anyone can create, edit and delete blog
posts. Let’s fix that. We’ll use HTTP Basic authenticate to put a password on
actions we don’t want everyone accessing. Open
app/controllers/posts_controller.rb and add
except: [ :index, :show ] on line 2 just below the class declaration. At the
bottom of your file put the following code:
private def authenticate authenticate_or_request_with_http_basic do |name, password| name == "admin" && password == "secret" end end
posts_controller.rb should have the following code at the top
and the bottom of the file. Note that all the methods are excluded here for
class PostsController < ApplicationController before_filter :authenticate, except: [ :index, :show ] before_action :set_post, only: [:show, :edit, :update, :destroy] ... # all your actions go in here ... private ... # there should be post_params and set_post methods in here. ... def authenticate authenticate_or_request_with_http_basic do |name, password| name == "admin" && password == "secret" end end end
With that code in place you can try to add a new post and you’ll be prompted to enter a username and password.
Creating a database model and routing
No blog is complete without comments. Let’s add them in. On our command prompt,
shut down your rails server by hitting
Ctrl-C and then type in:
rails generate resource Comment post:references body:text
Then you’ll want to update your database here to reflect the schema change you’ve just made:
After this you’ll need to inform Rails that your Posts will potentially have
many Comments. Open
app/models/post.rb and add the line:
somewhere inside the class. This should look like:
class Post < ActiveRecord::Base has_many :comments validates_presence_of :body, :title end
The back-end for your comments is almost complete, we only need to configure
the url that is used to create your comments. Since comments belong to a post, we’ll make the URL reflect this. Right now you can see all the configured URLs
rake routes in your command prompt. If you do this now you’ll get
something like the following:
comments GET /comments(.:format) comments#index POST /comments(.:format) comments#create new_comment GET /comments/new(.:format) comments#new edit_comment GET /comments/:id/edit(.:format) comments#edit comment GET /comments/:id(.:format) comments#show PUT /comments/:id(.:format) comments#update DELETE /comments/:id(.:format) comments#destroy posts GET /posts(.:format) posts#index POST /posts(.:format) posts#create new_post GET /posts/new(.:format) posts#new edit_post GET /posts/:id/edit(.:format) posts#edit post GET /posts/:id(.:format) posts#show PUT /posts/:id(.:format) posts#update DELETE /posts/:id(.:format) posts#destroy
Your URLs (or routes) are configured in all Rails applications in the file
config/routes.rb, open it now and remove the line
rake routes and you’ll notice that all the URLs for comments have
disappeared. Update your
routes.rb file to look like the following:
Rails.application.routes.draw do resources :posts do resources :comments, only: [:create] end # root 'welcome#index' end
Because comments will be visible from the show Post page along with the form
for creating them, we don’t need to have URLs for displaying comment listings,
or individual comments. When you rerun
rake routes you’ll now see the
post_comments POST /posts/:post_id/comments(.:format) comments#create
Before we’re finished with the backend for our commenting system we need to write the action that will create our comments. For more information on actions please read the Rails Guide on ActionController.
app/controllers/comments_controller.rb and make your code look like the
class CommentsController < ApplicationController def create @post = Post.find(params[:post_id]) @comment = @post.comments.create!(comment_params) redirect_to @post end private def comment_params params.require(:comment).permit(:body) end end
The big difference here from the Rails 3 guide is that we use a method called
comment_params to only choose the parameters from the form that we want to
save to the model. You can read more about this at:
Putting comments into your HTML view
You’ve created the database model for your comments, migrated your database,
informed Rails of the relationship between comments and posts, configured a
URL that lets you create your comments and created the controller action that
will create the comments. Now you need to display any comments that have been
submitted for a post, and allow users to submit comments. Open
app/views/posts/show.html.erb and make it look like:
<p id="notice"><%= notice %></p> <%= render partial: @post %> <%= link_to 'Edit', edit_post_path(@post) %> | <%= link_to 'Back', posts_path %> <h2>Comments</h2> <div id="comments"> <%= render partial: @post.comments %> </div>
You’ll now need to create a file called
with the following contents:
<%= div_for comment do %> <p> <strong> Posted <%= time_ago_in_words(comment.created_at) %> ago </strong> <br/> <%= comment.body %> </p> <% end %>
app/views/posts/show.html.erb you need to add in the form for
submitting a comment so add the following code to the bottom of that file.
<%= form_for [@post, Comment.new] do |f| %> <p> <%= f.label :body, "New comment" %><br/> <%= f.text_area :body %> </p> <p><%= f.submit "Add comment" %></p> <% end %>
Comments are now working (if they aren’t make sure you restart your
server), so go ahead and browse to your
post and add a new comment.
Publishing your Blog on the internet
Heroku is a fantastically simple service that can be used to host Ruby on Rails applications. You’ll be able to host your blog on Heroku on their free-tier, but first you’ll need a Heroku account. Head to https://www.heroku.com/, click Sign Up and create an account. The starter documentation for Heroku is available at: https://devcenter.heroku.com/articles/quickstart. Once you’ve got an account you’ll need to download the toolbelt from https://toolbelt.heroku.com/ and set it up on your computer.
Make the application work on Heroku
Up until this point we’ve been using SQLite as our database, but unfortunately Heroku doesn’t support the use of SQLite. So we’re going to be running Postgres instead.
We need to do some other things to make our application work on Heroku (it has to follow the “Twelve-Factor” rules – don’t worry about the details).
These changes are easy to make. You’ll need to open the
Gemfile and make
Gemfile look like:
source 'https://rubygems.org' gem 'rails', '~> 4.0.5' gem 'sqlite3', group: [:development, :test] gem 'pg', group: :production gem 'sass-rails', '~> 4.0.3' gem 'uglifier', '>= 1.3.0' gem 'coffee-rails', '~> 4.0.0' gem 'jquery-rails' gem 'turbolinks' gem 'jbuilder', '~> 2.0' gem 'sdoc', '~> 0.4.0', group: :doc gem 'spring', group: :development gem 'rails_12factor', group: :production
After this, run the command
bundle install --without=production on your
Regarding version control
Heroku also requires that every application is placed under version control before it is deployed. Simply run the following commands on the command prompt to make sure your application is properly controlled:
git init git add . git commit -m "initial blog commit"
Deploying your application
In the same command prompt you should be ready to deploy your application. First we create our Heroku application:
Now we push our application to Heroku:
git push heroku master
Finally we set up our database:
heroku run:detached rake db:setup
This setup of the database should only need to take place the first time you
deploy to heroku. Afterwards you may need to run
heroku run rake db:migrate instead. The
detached option runs the command in the background. It is there only to
ensure the process will go through, even on faulty Internet connection. You can
heroku logs to view the output of the command.
Finally you should be able to browse to the URL that Heroku has given you and check to see that your blog has been deployed properly!
Welcome to Ruby on Rails. If you’re this far along you should definitely head on over to Part 2 which goes more in depth with Rails and begins to add more features to the blogging engine.