Rails 2.1 introdcution with scaffolding

Okay, after settig up rails 2.1 we are now ready to start our rails journey. So lets begin with a simple blog application. If you are thinking why are we not following the tradition of “Hello World” project here,  the answer is simple, because you can find it all over the internet. For the sake of simplicity of this beginner introduction we assume we just want to create posts and add comments to our blog. No categories and no other bells and whistles, because the main point is to learn rails 2.1 neither to learn how to create a blog.

Creating the project

First thing is to create rails project and for this purpose we use rails command. But there is one thing you need to remember by default rails setup the project’s database to sqlite, so you need to change it to mysql by using the -d option with rails command, so lets create our project.

Command:

rails -d mysql bloggy

You will see bunch of lines passing by on your screen, these are all messages from rails about creating the directory structure that is required to build our web app in rails. If you will view your directory listing now you will find a new directory bloggy there, this directory contains subdirectories and files that are being created by the above command. Now change your directory to the bloggy directory.

NOTE: This is important because from now on we will assume that we are in bloggy directory.

Directory Structure

There are 2 directories that are of our interest for now and those are app and config. First talk about config directory, it contains configuration files which you never need to change if you follow purely rails way of developing your web application. But the important files there are database.yml, environment.rb and routes.rb. We will see later what these files are for but for now just remember that they are in the config sub directory under our main project directory.

Role of the Controllers

The other sub-direcotry app contains 4 other sub directories, controllers, models, helpers and views. As rails uses MVC approach for development the code is separated in those sub directories. Controllers have all the decision powers and they are called controller because as soon as rails gets a request the first thing it do is matches the url against routes.rb file in config directory and then give the control to the respective controller and from there controller decides what model to call and what view to use. Now you must be asking what are models?

What are Rails Models?

Models are interface to your database, so instead of writing SQL in your app you use model objects. You create class which represents table in your database, you instantiate class in your code and that represents a row in the table, and attributes of that object represents columns of that row. So you don’t write SQL at all just use Models to talk with your database. Now lets get to know what are views so we can gets our hand wet with some rails in practical.

What are Rails Views?

Views contain the code that will create your site’s interface, that is actually viewable by user and hence view sub directory contains further sub directories which contain html + some ruby code for that controller.

Convention over Configuration

Although Rails prefers convention over configuration, so if you just place everything in its place you just have to worry about coding your app rather then to change any configuration files. But there is one configuration file that needs to be changed, that is your database configuration file database.yml which is located in config directory. By default database.yml contains following:

# MySQL.  Versions 4.1 and 5.0 are recommended.
#
# Install the MySQL driver:
#   gem install mysql
# On Mac OS X:
#   sudo gem install mysql -- --with-mysql-dir=/usr/local/mysql
# On Mac OS X Leopard:
#   sudo env ARCHFLAGS="-arch i386" gem install mysql -- --with-mysql-config=/usr/local/mysql/bin/mysql_config
#       This sets the ARCHFLAGS environment variable to your native architecture
# On Windows:
#   gem install mysql
#       Choose the win32 build.
#       Install MySQL and put its /bin directory on your path.
#
# And be sure to use new-style password hashing:
#   http://dev.mysql.com/doc/refman/5.0/en/old-client.html
development:
adapter: mysql
encoding: utf8
database: bloggy_development
username: root
password:
socket: /var/run/mysqld/mysqld.sock

…rest of the file skipped…

The lines starting with ‘#’ are comments and followed by the first comment block is the development database clause and that is what we are interested for now. The other databases are production and test, the name suggests what they are used for. So our main concerned now is development db as we are still in the development stage. So now we should provide valid credentials for development database, the file is self explanatory and hopefully you know how to edit text files and save them. So update your database.yml with correct credentials and save the file.

Creating the databae

Now run the following rake command to create the database for your application.

rake db:create

Don’t worry about rake its just a “make” like utility which allows you to perform common rails tasks without worrying much about them. So now we have our rails project and database ready. Now we will generate some scaffolds.

Generating Scaffolds

Now there is one more directory that I want to introduce to you, the script sub directory under your project main directory. The script directory contains scripts to allow you to interact with your rails framework. The few main scripts are server (a development web server that allows you to quickly test your app via browser), console (load your rails environment and then gives you ruby prompt) and generate (this is your friend who writes code for you ;)). So we know that generate script is our friend so how do we use it?

Back to our blog application what models to we need? As we decided earlier we will only allow posts and comments. So that means 2 models a Post model and a Comment model. So, first we will create the scaffolding for our Post model. Following table lists the attributes we need for our Post model.

Attribute  |   Type    |   MySQL Type
title             string         varchar
body            text            text

Now to the practical part of it, how to create the scaffolding for the above model. The new scaffolding that has been introduced in Rails 2.1 has following syntax

ruby script/generate scaffold ModelName [field:type field:type ...]

We know our fields and types, so we will generate our scaffolding like following:

ruby script/generate scaffold Post title:string body:text

This will again show you bunch of lines on your screen showing what files has been created. We are almost done, just need to create the post table in our database, in rails terminology migrate our db to current version. And to accomplish this we will again use rake, so the following command will migrate our database to the most current version.

rake db:migrate

We are done with our scaffolding, now we can test our bloggy app, as it now supports creating posts. In the next part (coming very very soon) I will write how to add comments to the post, that will be part 2 of this post.

Viewing the outcome

Now to test our app we have to run the rails development web server using the following command:

ruby script/server

Output:

=> Booting WEBrick…
=> Rails 2.1.0 application started on http://0.0.0.0:3000
=> Ctrl-C to shutdown server; call with –help for options
[2008-07-25 11:52:33] INFO  WEBrick 1.3.1
[2008-07-25 11:52:33] INFO  ruby 1.8.6 (2007-09-24) [i486-linux]
[2008-07-25 11:52:33] INFO  WEBrick::HTTPServer#start: pid=4763 port=3000

You should see the above output, from the above output we can see our webserver is running on port 3000 so now we will open our web browser and browse to the URL: http://localhost:3000/, you should see “Welcome aboard” message from rails that means web server is running fine.

welcome aboard

Now browse to the http://localhost:3000/posts to test our scaffolding that we have generated yet. You should see something like following:

Command Summary:

  1. rails -d mysql bloggy
  2. rake db:create
  3. ruby script/generate scaffold Post title:string body:text
  4. rake db:migrate
  5. ruby script/server

Practice

I hope you have been successfully following till here. Now spend sometime getting to know the scaffolding generated, view the code generated for controller, model and views. Get your self familiar with it, ask questions for what you don’t understand. In the next part we will add comments functionality in our blog app. If you like to be updated you can subscribe to the feed.

Published by

Hameedullah Khan

VR enthusiast, Cloud Architect, Passionate Programmer and Opensource advocate.

2 thoughts on “Rails 2.1 introdcution with scaffolding”

Leave a Reply

Your email address will not be published. Required fields are marked *

CommentLuv badge