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:
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:
ModelsA 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.ViewsViews 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.ControllersControllers 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:
For Further Reading,