Quick Rails 4 Blog Tutorial

of 01

Quick Rails 4 Blog Tutorial

What do you do when a new version of Rails comes out? Build a blog, of course. The blog is kind of the "hello world" application of the web application world. It's simple enough to be implemented (if you know what you're doing) in a few minutes, but complex enough to show off the features of Rails. And as Rails evolves, so does the blog. The following tutorial is a very quick and rough blog in Ruby on Rails 4.

Install Rails and Generate Project

Before installing a new version of Rails, I like to switch to a new RVM gemset. If you're not using RVM, don't worry about this step.

$ rvm use @rails4 --create

Installing Rails 4 is as easy as it ever way, just use gem install. Make sure you add --no-rdoc and --no-ri, Rails is big and the documentation takes forever to install. There are better ways of reading the docs anyway.

$ gem install rails --no-rdoc --no-ri

Time to generate a new project. Change to a suitable directory and run rails new blog, this will create a new blog directory with your stub project in it.

$ rails new blog


Good old scaffolding, as old as the "Woops!" demo (though changed dramatically). To get off the start line fast, we'll scaffold a Posts model and controller. A blog post has (for right now, remember with migrations you can always add new things later) a title and a body. Rails takes care of the date the post was created, so we don't have to worry about that. The types of these should be string and text. The difference being a string is a shorter column with a maximum length (which varies depending on your database), while text is an unlimited blob of text.

$ rails generate scaffold post title:string body:text

And then migrate the database. The migration that was generated by the scaffold generator is in db/migrations should you want to check it out (and you should at least give it a once-over to see what it did).

$ rake db:migrate

Great, now start the server and head on over to http://localhost:3000/posts and create a few test posts. The interface is not very bloggy right now, but we'll fix that in a moment.

$ rails server

Posts as Default Controller

If you visit the root URL, you'll see a Rails welcome page. To get rid of that, you'll need to add a default route. Routes are Rails' way of mapping URLs to controllers and actions, and are configured in config/routes.rb. You'll see a single line there (put there by the scaffold generator) and whole lot of comments. The comments are informative, and give you a quick understanding of what to do in this file, but I usually delete them. To set up a default route, add the following line to the top.

Blog::Application.routes.draw do
  root 'posts#index' resources :posts end 

In previous versions of Rails you'd also have to delete a file from the public/ directory, which is used for serving static files. This is no longer true, so you don't have to do that anymore.

Blog Formatting

Now you have a blog, you have posts, let's format them in a more blog-like manner. First, open up your Posts controller in app/controllers/posts_controller.rb and look at the index method. The only change we'll need to make here is to reverse the order of the blog posts. There are two ways to do this, we can do all the work in Ruby with the reverse method, or dig into ActiveRecord and tell the database to do it for us. We'll use the database here, so we need to use the order parameter to the all method. We'll want to order by created_at (a field that's automatically populated by Rails whenever it creates a new resource) in the descending direction. It should now read as follows.

def index
  @posts = Post.all(:order => 'created_at DESC')

Now they're in the right order (newest on top), let's display them in a more blog-like and less table-like manner. All we need here is a few divs and simple_format. The simple_format method is useful for cramming plain text into HTML (which largely ignores whitespace). It will encapsulate paragraphs in paragraph tags and generally get things looking right quickly, but there are certainly better ways of doing this. So the work being done here is being done in a view which you can find at app/views/posts/index.html.erb. The entire file should now look like this.

<div id="posts">
  <% @posts.each do|post| %>
  <div id="post">
    <h3><%= post.title %></h3>
    <%= simple_format post.body %>
      <%= link_to 'Edit', edit_post_path(post) %> |
      <%= link_to 'Destroy', post, method: :delete, data: { confirm: 'Are you sure?' } %>
  <% end %>

<%= link_to 'New Post', new_post_path %>


This tutorial is much too short for any proper authentication, but we can use some simple authentication with a hard-coded username and password for now. This isn't something you'd want to keep in a production application, but it's quicker than messing with Devise for such a simple application.

To get this up and running, use the http_basic_authenticate_with method in your controller. It takes three parameters, the :name, :password and :except parameters. Name and password are username and password in plain text, and the except parameter is a list of methods that don't need authentication. Whitelisting is used so you don't accidentally leave any actions open. The only actions we don't want open are index and show.

class PostsController < ApplicationController
  before_action :set_post, only: [:show, :edit, :update, :destroy]
  http_basic_authenticate_with name: "admin", password: "12345", except: [:index, :show] 


Of course this blog isn't finished, but it is a working Rails application. Some things to consider are giving it some style with CSS, formatting with RedCloth or similar, adding real authentication with Devise, etc.