Creating Your First Ruby on Rails Application From Scratch
This tutorial which will help you create a basic Ruby on Rails application, without worrying too much about Ruby basics for now. Well, if you want to learn more about Ruby or Rails basic concepts, please refer the following links:
And if you need more help, you can hit the #railsbridge channel of freenodeIRC.
So what are you waiting for? Lets get started with creating our basic rails application!
Getting Started
What is Ruby
Ruby is one of the easiest scripting languages I have ever seen; simple enough for non-tech people, powerful enough for advanced programmers and best of all, it doesn’t have a complex syntax or keywords to be memorized. Instead it is written in a simple English syntax.
What is Rails
Rails is a web development framework written in the Ruby language, which has a general MVC (Models, Views, Controllers) type of structure to make everything simple for the developers. It allows you to write less code but accomplish more than most other languages/frameworks.
Rails MVC Architecture

Rails has a MVC (Models, Views, Controllers) architecture and its benefits include:
From Getting Started With Rails
Models
A model represents the information (data) of the application and the rules to manipulate that data. In the case of Rails, models are primarily used for managing the rules of interaction with a corresponding database table. Most often, a single table in your database will correspond to a single model in your application. The bulk of your application’s business logic will be concentrated in the models.
Views
Views represent the user interface of your application. In Rails, views are often HTML files with embedded Ruby code that performs tasks related solely to the presentation of the data. Views handle the job of providing data to the web browser or other tool that is used to make requests from your application.
Controllers
Controllers provide the “glue” between models and views. In Rails, controllers are responsible for processing the incoming requests from the web browser, interrogating the models for data, and passing that data on to the views for presentation.
Welcome to Rails!
Now lets create the sample ‘Slambook’ Application.
Requirements:
(Note: I will be using ubuntu (linux) and Postgres for building my rails application, but you can also install rails on your Windows or Mac machine as well.]
Once you have everything installed, we can start creating our rails application. To begin, open a terminal (Console, Command Prompt, etc) and type the command:
rails slambook
For this example we will use ’slambook’ as the name of the application which we will build. As soon as you hit enter, you will see the scripts flow in your terminal creating a bunch of files (as seen in the picture below):

These are the files which rails automatically generates to create the framework for our application.
Now just change the directory to our application using:
cd guestbook
and feel free to explore all the sub-directories and the files inside it to get an idea where the code lives.

Now, lets test if your rails application is working by using the command:
script/server
Open your favourite browser and type http://localhost:3000/ in the address bar and press Enter.


If you see a page similar to the above image, then your first rails application works fine (pat yourself on the back, you got it right)!
To start off, we are going to create the needed controller, model and views for our guestbooks post functionality which allows your friends to sign your ’slambook’.
Using the command:
$script/generate scaffold post name:string address:text dob:date desire:text interests:text hobby:text signature:text

Scaffold command creates a CRUD (Create, Read, Update, Delete) interface for your app ( a quick way of creating the MVC automatically). Alternatively, you can also create your controller, model and view manually using the command
$script/generate controller <controller name> // for creating controller and views
$script/generate model <model name> // for creating model
Here we are telling rails that we want code generated to handle a “Post” model, which has a string type for name and text for address, date for dob and so on. Notice this will generate some more files, one of which is the database migration file found inside the db/ directory

This is how our first migration file looks (slambook application):
The migration files are used for managing the CRUD (create, read, update and delete) activities of the database. If you haven’t created your database yet we can do it by a command:
$rake db:create
Now you might wonder how rails connects our database, and for this purpose we provide our database information in the database.yml file which is found inside the config/ directory:

This is how the database.yml file looks. We mention our database name and user details for rails to make the connection.
Since now we have recently created a new model for Post, a table must be created in our database and requires that we upgrade the database using this command:
$rake db:migrate // (instead of creating/updating the database table manually)
This updates the database with the information from the migration file.
(Note: when this command is executed, the migration file inside the db/migrate/ directory say 20090718013114_create_posts.rb is used as an reference for updating the database)
Now lets checkout what we have done so far:
$script/server
As before, open your browser and type http://localhost:3000/posts in the address bar and press Enter to see your application:

If your page looks like that, then shout “Wow! I have created my first rails application!”
The page at http://localhost:3000/posts shows the list of post made in your guestbook. Note there you have a link “New Post” which links to the the page at http://localhost/posts/new where your friends can sign your guestbook. You must wonder how these pages were created, so take a look at the app/views/posts directory which contains the html pages that were created by the scaffold command. These html pages have .html.erb extension which means ruby code can be embedded in your html files.
Now lets create a home page for our ’slambook’ application:
$script/generate controller home index
This creates a controller “home” along with views in the app/view/home directory. Rails will create several files for you, including app/views/home/index.html.erb file. This is the template that we will use to display the results of the index action (method) in the home controller. Open this file in your text editor and edit it to contain the code that you want to display in your index page:
<h1>Magesh's Slam-book or Guestbook</h1> <%= link_to "View my book", posts_path %> <%= link_to "Sign my book", new_post_path %>
The last two lines have added two links in my home page, one for people to view all the posts in my slambook and the other for new friends to use to sign my slambook.
tag is used to display the link. posts_path links to the posts/index page and new_post_path links to the posts/new page.
I suggest you also open the other .html.erb files in app/views/posts directory like index.html.erb, show.html.erb, edit.html.erb and new.html.erb to have a look around. Their functions are described in the file posts_controller.rb (controller) inside the app/controller directory.

Dont get confused with the above image, I will tell you how it works:
Lets take the index method first:
def index @posts = Post.all respond_to do |format|
format.html # index.html.erb
format.xml { render :xml => @posts }
end
@posts variable stores all the posts and format.html is used to render the index.html.erb file in the app/views/posts directory.
Similarly the other methods such as new, edit and show are created. Notice that the methods inside the posts_controller.rb file are related to the files inside app/views/posts directory.
The show method renders the app/views/posts/show.html.erb file and in the same way the edit method renders the app/views/post/edit.html.erb file.
When you hit http://localhost:3000/ in your browser you should get the rails default page instead of our home page. That is because rails has created a default index.html page in the public directory. Since we want to use the home controller to show the index page instead of the rails default page ( public/index.html ), we must delete that public/index.html file first:
$rm public/index.html
and then tell rails to point to home controller as the default index page. That is done by editing the config/routes.rb file (rails routing)
Rails routing?
You can learn more about routing by reading Rails Routing from the Outside In.
Edit config/routes.rb in your favorite editor (I prefer emacs)
ActionController::Routing::Routes.draw do |map| map.resources :posts map.resources :home map.root :controller => "home"; map.connect ':controller/:action/:id' map.connect ':controller/:action/:id.:format'
Note: Whenever a controller is created we need to inform rails about it using the map.resources : which creates the url say http://localhost/ in our application.
Also check out the 4th line: map.root :controller => “home” tells rails to load the home controller for the default home page.
Now visit http://localhost:3000/ and you should see our new home page:

Conclusion
So this is just the skeleton of our application. We obviously should add CSS to design our rails application to make everything look better!
I hope this helps you start Ruby on Rails with ease! If you have any queries or are facing any problem while trying out this on your machine please feel free to shout your comments below. ;)
Magesh is a passionate web developer in Chennai, India working with Ruby on Rails, Javascript, jQuery, and AJAX. Additionally, he loves working with open source tools & Linux, and loves social networking. He has been inspired by the web to become an entrepreneur. Twitter.


Is this the whole article? I seem to be missing the part where we actually make something…?
Yes… the whole article is missing…. checking into it now….
remove the &’s in the post (div class=”bar”) its not needed
The &’s are fixed…. and the gt and the lt ;)
Fixed. Thanks, it’s more useful now :P
Is there going to be more RoR tutorials like this?
I want to learn it now :)
i hope to do more posts on RoR, well i’ll try to make that for you :)
iam glad it helps you
Hey thanks for the tutorial. Its a good start to deploy a rails application, as I am very new to ruby.
I am unable to delete default index page with “rm public/index.html”. when I run the command, I got the error
‘rm’ is not recognized as an internal or external command,
operable program or batch file.
I am working on windows 7. Please help me out in fixing it.
Thanks
Nivedita
the ‘rm’ command is specific to UNIX-based systems. In Windows you should use the ‘del’ command instead.
Hope that helps!
yeah it worked….thanks for the help !!
Also one weird thing happening is after setting up my database, when I run commands
rake rails:freeze:gems
rake db:migrate
I am getting error “rake aborted!” no rake file to load
only few times I am getting this error, not all the times.
Some times, I was able to run those commands and built the migrations.
I never understand the reason behind it.
Please help me in fixing this error.
I am using mysql database and I configured accordingly in config/database.yml.
Also do we need to install the scaffold plugin for every application we run?
Thanks in Advance !!
Nivedita
Oh, one more thing. When you’re doing script/[command] commands on the command-line, don’t you need ruby before that, especially in Ubuntu?
As long as the Ruby binary is in your execution path ($PATH environment variable) and the scripts are chmod +x (which they will be if generated by the ‘rails’ command) you can simply type script/[command] and you’ll be fine.
yes.Before beginning you need to install ruby, if using ubuntu type apt-get install ruby in your Terminal
I think Ethan meant shouldn’t you have to type ‘ruby script/[command]‘ from the command line. (correct me if I am wrong) And the answer is yes, unless you are on a Mac. If you are on a Mac you can omit the ruby portion of the command. Not sure about Linux.
Also, I would like to see some posts on getting started with testing. A lot of people get the concept, but aren’t sure where to start or what they should test.
If Ethan meant that way(as scott ) then the answer is no, unless you are on a Mac or Linux machine.. you can type
ruby script/server (or)
script/server
(you can omit the ‘ruby’)
both means the same, but i’m not sure about Windows. i have tried this in most of the linux distros(Ubuntu, Fedora..).
Right, on linux/unix, Mac OS X, etc, you don’t need to prefix those commands with ruby if everything is set up correctly. On Windows I am pretty sure you do need to use Ruby before each command. In my experience though, its better to develop Ruby in a ‘nix/mac environment. Its normally closer to the systems you will be using for final deployment.
Yes, on WIndows you must prefix the command with ruby. I have developed Rails on both the Windows and Mac platforms. Windows is a huge pain. Mac is a breeze.
Yeah and developing rails in linux is much simple :) using emacs for the development(IDE/Text Editor) you get to do a lot of works simple. eg: running the server, navigating thru the app directory, viewing your mvc files.. saves you a lot of time
I’d like to see an updated tutorial (with the latest version of Rails) on how to deploy a ROR app from local to the actual server.
Thanks
I’ll try to write my next post on that (deploying ROR)
You are voted!
Track back from WebDevVote.com
hi magesh ur article s nice da… try to write more genius…………………….
thanks a lot :)
Hi Mahesh,
A good article but I love to see the real time deployment of the rails application. Since most of the time I wondering which environment I am working and what changes I need to do for the realtime deployment.
thankyou and i will try to make a post on it soon!!
you mentioned to do rails slambook but in next step you told to change directory to cd guestbook!!
But no doubt a good article helped me a lot.
cheers
yes, before ‘change directory’, i have also mentioned about the command $rails guestbook, which creates the application directory. And iam glad it helped you. If you have any other doubts feel free to ask me here :)
It really helped me a lot :)
Thanks for the great walkthrough. Very well written for people not that familiar with RoR (me). Thanks.
how do i do testing in ruby on rails?? after creating the application ..
do u mean testing in the browser? if yes then check out cucumber..
for writing tests do check this http://guides.rubyonrails.org/testing.html
Hi Magesh,
I am good in java and wanted to learn Ruby on Rails. Your article had helped me a lot to learn quickly my first ruby on rails app. Nice explanation.
Thanks,
Venkat
Really well done.. I feel like I have some basic understanding now to move forward. This tutorial was a nice way to explain the basic framework in order to get the big picture. Now I can go and dive into the details. It helps to a get a general sense of how this works before getting started. Thanks so much!
howdy there, i just discovered your site listed on google, and i must say that you express exceptionally well on your site. i am very moved by the method that you write, and the subject is excellent. in any event, i would also like to know whether you would love to exchange links with my website? i will be certainly more than happy to reciprocate and put your link off in the blogroll. anticipating for your answer, thanks and enjoy your day!
@venkat @mariam: i’m glad it helped you :)
I am very confused reg installing gems. where do i need to install them? in the directory where ruby is installed or in every rails application that is created? same doubt about gem install mysql also.
also i am not able to run rake db:migrate, though I can run rake rails:freeze:gems
And when I run gem install mysql, i am getting this
C:\Documents and Settings\Nivedita\autograph>gem install my
Successfully installed mysql-2.8.1-x86-mswin32
1 gem installed
Installing ri documentation for mysql-2.8.1-x86-mswin32…
No definition for next_result
No definition for field_name
No definition for field_table
No definition for field_def
No definition for field_type
No definition for field_length
No definition for field_max_length
No definition for field_flags
No definition for field_decimals
No definition for time_inspect
No definition for time_to_s
No definition for time_get_year
No definition for time_get_month
No definition for time_get_day
No definition for time_get_hour
No definition for time_get_minute
No definition for time_get_second
No definition for time_get_neg
No definition for time_get_second_part
No definition for time_set_year
No definition for time_set_month
No definition for time_set_day
No definition for time_set_hour
No definition for time_set_minute
No definition for time_set_second
No definition for time_set_neg
No definition for time_set_second_part
No definition for time_equal
No definition for error_errno
No definition for error_sqlstate
Installing RDoc documentation for mysql-2.8.1-x86-mswin32..
No definition for next_result
No definition for field_name
No definition for field_table
No definition for field_def
No definition for field_type
No definition for field_length
No definition for field_max_length
No definition for field_flags
No definition for field_decimals
No definition for time_inspect
No definition for time_to_s
No definition for time_get_year
No definition for time_get_month
No definition for time_get_day
No definition for time_get_hour
No definition for time_get_minute
No definition for time_get_second
No definition for time_get_neg
No definition for time_get_second_part
No definition for time_set_year
No definition for time_set_month
No definition for time_set_day
No definition for time_set_hour
No definition for time_set_minute
No definition for time_set_second
No definition for time_set_neg
No definition for time_set_second_part
No definition for time_equal
No definition for error_errno
No definition for error_sqlstate
autograph is my rails application.
I am using windows vista
i tried on windows 7 too
same situation.
Please help me out. I am really in a hurry in finishing the project. I just had two more days to go.
Thanks in advance
I forgot to mention about rails version I am using
rails 2.3.8
ruby 1.8.6
gems 1.3.7
mysql 5.0.67
I am using mysql 5.0.67 because I read in some blog that it is compatible with ROR
I was not able to connect mysql 5.1.47 to ROR
I have tried this but in half way I get stuck.. I dont know wats the prob. http://localhost:3000/ is working but when i change to http://localhost/details is not working. the page created is like this
ActiveRecord::StatementInvalid in DetailsController#index
Mysql::Error: Table ‘hi.details’ doesn’t exist: SELECT * FROM `details`
RAILS_ROOT: D:/RekhaMol/Rails/New
Application Trace | Framework Trace | Full Trace
C:/Ruby186/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/connection_adapters/abstract_adapter.rb:221:in `log’
C:/Ruby186/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/connection_adapters/mysql_adapter.rb:323:in `execute’
C:/Ruby186/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/connection_adapters/mysql_adapter.rb:638:in `select’
C:/Ruby186/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/connection_adapters/abstract/database_statements.rb:7:in `select_all_without_query_cache’
C:/Ruby186/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/connection_adapters/abstract/query_cache.rb:60:in `select_all’
C:/Ruby186/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/connection_adapters/abstract/query_cache.rb:81:in `cache_sql’
C:/Ruby186/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/connection_adapters/abstract/query_cache.rb:60:in `select_all’
C:/Ruby186/lib/ruby/gems/1.8/gems/activerecord-2.3.8/lib/active_record/base.rb:664:in `find_by_sql’
Please tel me how to correlate the model, view and the controller. How the working goes and how each works interactively.
Please tel me how to correlate the model, view and the controller. How the working goes and how each interactively.
Awesome!! Exactly what i needed.
This is the best tutorial for beginner that I saw in my life!!!! Works perfect for me. Thanks Magesh I’m very grateful.
Thanks for the tutorial, it really helped me make a start.
I hvae run across a resource (html5 boilerplate for rails), and wondered if you would consider doing a tutorial using it to show how to actually build and edit an actual website. There are so many tutorials showing how to create an app, start the server, but not so much about the building and editing a website. I thought perhaps with this GIT resource, it would help and you seem to have the knowledge to write it.
It is at https://github.com/paulirish/html5-boilerplate
Thanks, and great tutorial
amazing article…helped me alot in boosting my confidence…keep writting…this was just what i wanted to start my work in ROR…
Hi Magesh!
Very nice article!
But I am stuck up at the last point here. I didn’t get the part where we have to edit the routes.rb file. It contains a lot of stuff already. Do I need to erase it? When I edit the file I am getting following error in the browser.
Routing Error
No route matches [GET] “/”
Try running rake routes for more information on available routes.
I am using Windows 7 OS.
Hope you could help me with this.
Hey I did it. That was a very silly mistake.
But thanks a lot for your article. It is really very useful for a beginner.
How did you fix it? I’m getting the same error.
Very good article.
Hi, Magesh! Your article is great.
Can I get some help? Below is my routes. How to apply your routes in mine? It can’t work.
Slambook::Application.routes.draw do
get “home/index”
resources :posts
# The priority is based upon order of creation:
# first created -> highest priority.
Thank you in advance.
# Sample of regular route:
# match ‘products/:id’ => ‘catalog#view’
# Keep in mind you can assign values other than :controller and :action
# Sample of named route:
# match ‘products/:id/purchase’ => ‘catalog#purchase’, :as => :purchase
# This route can be invoked with purchase_url(:id => product.id)
# Sample resource route (maps HTTP verbs to controller actions automatically):
# resources :products
# Sample resource route with options:
# resources :products do
# member do
# get ’short’
# post ‘toggle’
# end
#
# collection do
# get ’sold’
# end
# end
# Sample resource route with sub-resources:
# resources :products do
# resources :comments, :sales
# resource :seller
# end
# Sample resource route with more complex sub-resources
# resources :products do
# resources :comments
# resources :sales do
# get ‘recent’, :on => :collection
# end
# end
# Sample resource route within a namespace:
# namespace :admin do
# # Directs /admin/products/* to Admin::ProductsController
# # (app/controllers/admin/products_controller.rb)
# resources :products
# end
# You can have the root of your site routed with “root”
# just remember to delete public/index.html.
# root :to => ‘welcome#index’
# See how all your routes lay out with “rake routes”
# This is a legacy wild controller route that’s not recommended for RESTful applications.
# Note: This route will make all actions in every controller accessible via GET requests.
# match ‘:controller(/:action(/:id))(.:format)’
end
I don’t know where to insert the routes either. Do we delete all data inside or add?
remove the # before the ‘#root:to=>’welcome#index’ and edit it to look like this ‘root:to=>’home#index’
Thank you for your great post
Nice article. Keep sharing :)
i need some sample projects in rails 3.1
i need some sample rails projects if possible plz send me to my email address
hai magesh…it’s a good article for beginners like me…but can you explain the process by manually without using the scaffold
thank you