Using the Ruby on Rails web framework – How to install Rails and create a simple blog (Part 1)

VN:F [1.9.22_1171]
Rating: 3.7/5 (7 votes cast)

This is a beginner’s guide to installing Ruby on Rails and creating a simple, secured blog relatively fast. Ruby on Rails is an open source MVC web application framework based on the Ruby programming language. It’s intended to be used with an agile development methodology that is used by web developers for rapid development. If you’ve not heard about the Agile development or the MVC concept, please read about them first, as you need to know about their basics to be able to understand all parts of this tutorial. Very basic knowledge of HTML and Ruby will be needed, too.

By default Ruby on Rails includes tools that make web development easier, such as scaffolding that can automatically construct some of the models and views needed for a basic website. Other tools are WEBrick, a simple Ruby web server and Rake, a build system. Together with Rails these tools provide a basic development environment.

Warning! I’ve created this simple blog application on my own web space that’s was hosted by Hostmonster, installing and using Ruby on Rails on other web hosting providers’ web spaces may (probably) be different and many of them won’t even support Rails. As I moved my website to an other hosting provider in January 2012, the working examples are no longer available here.

Before you start installing, I need to warn you again, that this guide is Hostmonster specific and the installation bit will only work if you have a Hostmonster account. If you’re not with Hostmonster, but you have Ruby on Rails set up on a different host or on your computer, skip steps 1, 2, and 3.


1. Prerequisites

If your developing on Hostmonster, you need to have SSH access enabled. Here’s how to do this on Hostmonster.

WEBrick isn’t necessary on a Hostmonster account and you’re not supposed to use it. This is because Hostmonster wants you to develop on their server instead of developing your Ruby on Rails application on your own computer where there might not be an Apache install which is pre-configured to use Rails on Hostmonster. “Yay” for the pre-configured Apache, but “Booooooo” for forcing us to develop on the server…

Also, you should use MySQL on your Hostmonster account, hopefully this isn’t an issue.


2. Installing Rails on Hostmonster

To begin, log into the Hostmonster server using SSH (I use the free PuTTY software as an SSH client, but there are many similar ones on the net to download).

PuTTY - Logged in

You’ll create a work directory and then cd into it. You can name it whatever you would like, such as “myrails”…

mkdir ~/myrails

cd ~/myrails

Create an application called “myblog”. How you create the application depends on what version of Rails is running on the Hostmonster server (currently 2.3.5). To find it out use the following command…

rails -v

If they’re still running Rails 2.3.5, you’ll need to create your application like this…

rails -D -d mysql myblog

Next, you’ll need to set up a subdomain for the blog to run on. To do this, log into cPanel on Hostmonster, go to the “Domains” section and click on “Subdomains”, then type “myblog” into the first text box, so your new subdomain would be “myblog.mydomain.com”. Click into the “Document root” field and make sure that it’s automatically changed to “public_html/myblog” (if not, fill it in manually).
cPanel - Creating a subdomainNow click on the “Create” button.

You’ve now created a new subdomain, which will contain your Rails application. Next, you’re going to make your application’s “public” directory be the root directory of that subdomain with the following commands…

cd ~/public_html/

rm -r myblog

ln -s $HOME/myrails/myblog/public $HOME/public_html/myblog

If you go to http://myblog.mydomain.com/ you will see the default Ruby on Rails welcome page.
Default  Rails welcome pageHowever when you click on the “About your application’s environment” link, you’ll probably guess that something’s still not 100% working. The welcome message tells you what to do, but remember, you’re working on a Hostmonster account, so just ignore the first two points the welcome page suggests, skip to the third one and set up your database.


3. Setting up the database

Go to the “Databases” section in cPanel and click on “MySQL Databases”. At the bottom of this page, you can to add a MySQL user for Rails to use. Let’s call it “myuser”.

Hostmonster prefixes your username to the MySQL user name, so it’ll be something like “username_myuser”. After creating the user, don’t forget to take a note of the password you used. Next, you’re going to create a database at the top of the page. Let’s name it “mydb”. Similarly to the user the database is going to be called “username_mydb”, too.

Rails supports having a development and a production mode as well, so you’ll have to create a second database. Name this “mydbdev”. Finally, we’re going to link “username_myuser” to the two databases.

Select “username_myuser” and “username_mydb” from the drop down section at the bottom of the page and click on “Add”.
Setting up databaseAt the next page, make sure the “ALL PRIVILEGES” checkbox is checked, then click the “Make changes” button.
MySQL - adding privilegesRepeat this step with “username_mydbdev” as well.

Next you’ll have to edit the database.yml file. Open ~/myrails/myblog/config/database.yml either in Hostmonster’s file editor or in any other applicable software and modify the “development” and “production” sections, adding the username, password, and database that you just created (you only need the change the capital letter bits). You’ll also need to replace the “socket” line with a line specifying the host…

development:
   adapter: mysql
   encoding: utf8
   database: USERNAME_mydbdev
   pool: 5
   username: USERNAME_myuser
   password: MYUSERPASSWORD
   host: localhost

production:
   adapter: mysql
   encoding: utf8
   database: USERNAME_mydb
   pool: 5
   username: USERNAME_myuser
   password: MYUSERPASSWORD
   host: localhost

… and just comment out the “test” section like this…

#test:
#  adapter: mysql
#  encoding: utf8
#  reconnect: false
#  database: myblog_test
#  pool: 5
#  username: root
#  password:
#  socket: /tmp/mysql.sock


4. Creating the database and its tables

You’re now going to create a “scaffold”. A scaffold will create a CRUD structure for information, the controllers, the views, and the routes necessary for the blog application. Let’s use SSH again…

cd ~/myrails/myblog

./script/generate scaffold Entry title:string text:text

This script just created:

  • a model called “entry.rb” (~/myrails/myblog/app/models/)
  • a new folder and view structure called “entries” (~/myrails/myblog/app/views/entries)
  • a new layout called “entries.rb.html” (~/myrails/myblog/app/views/layouts/)
  • a new helper file called “entries_helper.rb” (~/myrails/myblog/app/helpers/)
  • a new controller called “entries_controller.rb” (~/myrails/myblog/app/controllers/)
  • and a migration file called something like “20100506122509_create_entries.rb” (~/myrails/myblog/db/migrate/) with the following content…
class CreateEntries < ActiveRecord::Migration
   def self.up
      create_table :entries do |t|
         t.string :title
         t.text :text

         t.timestamps
      end
   end

   def self.down
      drop_table :entries
   end
end

… as you can see, the migration file is kind of a database schema.

The next thing is to run the migration process…

rake db:migrate

… and this will actually set up the database and the “entries” table for you with the “id”, “title”, “text”, “created_at” and “updated_at” fields, so Rails has created a few more fields than you originally wanted at the scaffolding process.
phpMyAdmin - Entries tableThis is to aid the application not to run into primary key and duplication problems.


5. Setting up rewrite rules

Now that the database is set up, you’ll need to add a way for Rails requests to be processed. You have to place Apache rewrite rules into an .htaccess file so that all non-static requests coming into your application are processed through FastCGI, the CGI that Hostmonster uses.

To create the .htaccess file, you’ll need to type the following line into your SSH application…

touch ~/myrails/myblog/public/.htaccess

The next step is to add the following to the currently empty .htaccess file (you’ll find it here: ~/myrails/myblog/public/)…

# General Apache options
AddHandler fcgid-script .fcgi
RewriteEngine On
RewriteRule ^$ index.html [QSA]
RewriteRule ^([^.]+)/!$ $1.html [QSA]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteRule ^(.*)$ dispatch.fcgi [QSA,L]
ErrorDocument 500 "ERROR: app failed to start properly"

… and that’s it! Your Ruby on Rails application is fully functional. You can check this on the welcome page clicking on the “About your application’s environment” link. When clicked, it should display your app’s version info, along with other necessary data.
Rails welcome page - working


6. Populating the database

To use the scaffold function, you’ll need to use the plural of the scaffold name (“entry” -> “entries”). Navigate to http://myblog.mydomain.com/entries and here you create, edit, and delete blog entries (along with their associated records). Add a couple of sample entries now.
Rails - populating the database


7. Making “Blog” the default application

The aim is to make http://myblog.mydomain.com display the Blog application. To do this, delete the index.html from your public folder…

rm ~/myrails/myblog/public/index.html

Now you’re going to change the routes for your application. Go to the following line in the routes.rb config file (~/myrails/myblog/config/)…

# map.root :controller => "welcome"

… and change it to…

map.root :controller => "entries"

Done! Now when you visit http://myblog.mydomain.com, the Blog application shows up by default.
Rails - Blog is now default


8. Setting up basic authentication

Right now, anyone can add or edit your blog posts and I’m sure you don’t want that. Let’s go to the ~/myrails/myblog/app/controllers/entries_controller.rb file and add some basic authentication to the “EntryController” class the following way…

class EntriesController < ApplicationController
   
   # ADD THIS LINE BELOW

   before_filter :authenticate, :except => [:index, :show]

   # END OF STUFF YOU NEEDED TO ADD HERE

   # GET /entries
   # GET /entries.xml
   def index
      @entries = Entry.all

      respond_to do |format|
         format.html # index.html.erb
         format.xml  { render :xml => @entries }
      end
   end

   ***
   ***
   ***

   def destroy
      @entry = Entry.find(params[:id])
      @entry.destroy

      respond_to do |format|
         format.html { redirect_to(entries_url) }
         format.xml  { head :ok }
      end
   end

   # ADD THE FOLLOWING BELOW THE "destroy" FUNCTION

   private

   def authenticate
      authenticate_or_request_with_http_basic do |name, password|
         name =="admin" && password == "adminsecpass"
      end
   end

   # END OF STUFF YOU NEEDED TO ADD HERE

end

Now when anyone tries to add, edit or destroy a blog post, the browser will ask for the username (“admin”) and the password (“adminsecpass”).
Rails - simple authentication


*** Part 2 of this tutorial will continue with adding comments to the blog posts, plus securing the application and adding styles to make it nicer. ***

Using the Ruby on Rails web framework - How to install Rails and create a simple blog (Part 1), 3.7 out of 5 based on 7 ratings
 

1 response:

  1. Using the Ruby on Rails web framework – How to install Rails and create a simple blog (Part 2) | Attila Szomor > web design and development blog

    This article is the follow up of “Using the Ruby on Rails web framework – How to install Rails and create a simple blog. In Part 1 of this tutorial (Step 1 to 8) you looked at how to install Rails on a Hostmonster web account[...]

  2.