How to Create a Blog from Scratch Using Ruby on Rails
Nilesh Patil
Founder
A Synopsis of Ruby on Rails
Ruby on Rails is a framework for the Ruby programming language that allows for the rapid construction of web applications. It accomplishes this by allowing you to focus on addressing your clients' problems rather than on constructing an infrastructure to support your clients' difficulties.
Let's face it: you don't want to create a database access layer for each new project.
You will also not want to use a fully functional MVC design on a regular basis. This is the fundamental point of frameworks; they provide a foundation upon which to build. This helps you to focus on the client's demands rather than the so-called yak shaving activities that can bog you down.
A Few Words About MVC
MVC (Model-View-Controller) is worth mentioning because it can be one of the things that inhibits people from adopting frameworks like Rails.
MVC is a pretty sophisticated programming topic; nevertheless, I will not recommend that you learn how to create the MVC pattern, but rather how to use it. With this in mind, let's take a look at what each letter in the acronym M.V.C. stands for and how they relate to web development.
Model
The model layer is where you declare the classes that will be used/stored by your application.
For example, if you want to save blog posts, you will have a "Post" model. The model can communicate with the database and retrieve and save data. This capability is inherited from the ActiveRecord superclass.
Any methods that operate on this data should also be included in the model.
View
The view layer's primary function is to return the appropriate HTML to be rendered on the user's browser. A view in Rails is contained in an erb (Embedded Ruby) file that contains both HTML and embedded Ruby statements.
Controller
Nothing would happen if the controller was not there. The controller communicates with the model in order to retrieve and save data.
It will then send any data from the model to the view. The view sends the generated HTML to the controller, who then delivers it to the user's browser.
MVC Summary
This is a very brief overview of MVC. I strongly advise you to read up on this subject because it is the key to mastering Rails.
This infosiatech.com article is an excellent resource for learning MVC with Rails. However, installing the framework and experimenting with it is the best way to learn.
Creating a new Rails Project for your Blog
You must first start a new project before you can do anything else. A project in Rails is a folder structure that is used to hold all of the files that are important to your web application.
To create a project, key the following command at the command prompt:
> rails myblog -d mysql
Note in this case we are using MySQL as the DBMS. This command will create a folder called myblog that holds all the relevant project folders.
Important Files and Folders
- config\database.yml This file is a YAML (stands for – YAML Ain’t a Markup Language) file. It contains details about your DBMS provider and the authentication details for your DBMS.
- config\routes.rb This is a ruby file. It allows you to configure how HTTP requests will be routed.
- app\controllers Contains controller files. Controllers are ruby files.
- app\helpers Contains helper files. Helper files are ruby files which are used to define logic which doesn’t belong in the model but is too long-winded to be embeded in the view.
- app\models Contains model files. Model files are ruby files. They inherit most of there functionality from ActiveRecord but you can also build upon this functionality by writing your own methods.
- app\views Contains a sub folder for each controller file that exists. For instance, if there is a controller called “posts_contoller.rb” there will be a view sub-folder called “posts”.
- public\images Contains any image files that belong to your website.
- public\javascripts Contains any javascript files that are used by your website.
- public\stylesheets Contains any CSS files that belong to your website.
- db\migrate Contains “migration” files, used to migrate a database from one state to another.
Application Design
To build a Rails application, you must consider how the constituent data structures will interact with one another.
There are other degrees of design that you can implement; however, for the sake of simplicity, we will keep things basic.
So you've decided to create a blog application; where should you begin? First, get a pen and some paper and write a brief description of your application and what it should accomplish.
When you're finished, highlight/underline the nouns that must be stored in the database. A sentence will suffice for our small blog application:
"My app is a web log (blog)." It will enable me to publish posts and allow others to remark on them."
As a result, we require models for postings, persons (or users), and comments.
Again, in order to keep things simple, we can overlook people/users. So we'll need a model for both posts and comments.
Relation
you will need to think about how the models should relate to each other. The most common relationships in Rails are defined as follows:
- One-to-One
- One-to-Many
- Many-to-Many
You must consider the relationship between the models presented. With posts and comments, a particular post may have multiple comments, and a comment may belong to more than one post. This reasoning implies a One-to-Many link.
We shall return to relationships later.
Scaffolding
Scaffolding can be used to create quick prototypes or mock-ups for your client. They're also great for learning how to utilise Rails. You can create a model, controller, and numerous views with a single command, thereby building a significant amount of functionality in one fell swoop.
Creating Posts using Scaffolding
To create the relevant scaffold files for posts, you can generate them with a single command:
> ruby script/generate scaffold post title:string body:text
This command generates a large number of files.
It generates a controller for posts called posts_controller.rb as well as a model called post.rb (not plural). It also generates a posts subfolder in the views folder. There are four files in this package: index.html.erb, edit.html.erb, show.html.erb, and new.html.erb.
You may have also noted that we have provided the required fields, namely title and body, as well as their respective types "string" and "text".
Creating Comments using Scaffolding
Similarly, to create the relevant scaffold for comments, run this command:
> ruby script/generate scaffold comment name:string body:text post:references
You may have seen the text "post:references" at the end of this command. This will be used to generate the foreign key field for linking to the posts table's primary key.
Relating the Post and Comment Models
Now that you have two models, you must establish a relationship between them. To accomplish this, add the following code to both the post and comment models:
post.rb
class Post < ActiveRecord::Base
has_many :comments
end
comment.rb
class Comment < ActiveRecord::Base
belongs_to :post
end
This makes it quite simple to locate related records. You'll see how simple it is later when we need to display comments relating to a specific post.
How can I make a database and tables?
Now that you have created the models, you need to create the database then create tables to hold information about posts and comments.
To create the database you need to add the username and password into database.yml file, similar to below.
development:
adapter: mysql
encoding: utf8
reconnect: false
database: myblog_development
pool: 5
username: root
password: root
host: localhost
After you've updated the database.yml file with your database logon information, execute the following rake command from a command line.
Also, make sure your current directory is set to the project folder first:
> cd myblog
> rake db:create
The database should now be created.
Database Migration
A Migration is the term used in Rails to describe the process of changing your database from one state to another. Here are some examples of database migrations from one state to another:
- Creating tables
- Removing tables
- Adding new fields
- Removing fields Several files were created automatically when you used scaffold to create the two models for posts and comments. Migration files, in particular, were created in the db/migrate sub directory. These files are used to generate the post and comment model's tables.
To build the tables using the migration files you should run the following command:
> rake db:migrate
The “posts” and “comments” tables should now be created.
Let’s See How Things Look! Ok, lets fire up Webrick, Rails built-in web server, and see how things look.
> ruby script/server
Now, in your preferred browser, navigate to http://localhost:3000/posts and you should see a screen similar to the one below. By default, this URL request sends control to the posts controller's "index" method, which subsequently renders the "index.html.erb" view.
Follow The Step
- If you click the “New Post” link, highlighted, you will be directed to the URL, http://localhost:3000/posts/new, where you will be presented with a form for creating new posts. This URL request calls the “new” method in the posts controller, then the “new.html.erb” view is rendered.
- Click on the “Create” button to save your post, this will direct you to the URL, http://localhost:3000/posts/show/1, displaying the post details.
- This URL request calls the “show” method in the posts controller. It also passes one parameter, “1”, to the show method. Finally, it renders the “show.html.erb” view.
- Setting up a Home Page: You’ll likely want to have the root URL (http://localhost:3000) direct the user towards your posts, effectively making it your home page.
To do this you will first need to delete the public/index.html file.
- The second thing you need to do is set up a route in your config\routes.rb file. Open this file in notepad (or your favourite editor) and add a new line to the end using map.root, as shown below.
Route Changes
ActionController::Routing::Routes.draw do |map|
map.resources :comments
map.resources :posts
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
map.root :controller => "post"
end
Note: This route file has all the commented lines removed for the sake of clarity and conciseness. For more on routes, try the Rails API Documentation
Allow the User to Comment! Modify the Route Before making any changes to the view, you need to scope the “comments” route within the “posts”. Modify the route.rb file to look like the code below.
Route Changes
ActionController::Routing::Routes.draw do |map|
map.resources :posts, :has_many => :comments
map.connect ':controller/:action/:id'
map.connect ':controller/:action/:id.:format'
map.root :controller => "post"
end
Modify the View
Now modify the views/posts/show.html.erb file to be the same as the code below. Here, we are rendering the post, showing any related comments and then displaying a form to add new comments.
<p>
<b>Title:</b>
<%=h @post.title %>
</p>
<p>
<b>Body:</b>
<%=h @post.body %>
</p>
<h2>Comments</h2>
<% @post.comments.each do |c| %>
<p>
<b><%=h c.name %> said:</b><br />
<%= time_ago_in_words(c.created_at) %> ago
</p>
<p>
<%=h c.body %>
</p>
<% end %>
<% form_for [@post, Comment.new] do |f| %>
<p>
<%= f.label :name, "Author" %><br />
<%= f.text_field :name %><br />
<%= f.label :body, "Comment Description" %><br />
<%= f.text_area :body %>
</p>
<p>
<%= f.submit "Add Comment" %>
</p>
<% end %>
Modify the Comments Controller
Remove all the methods that were automatically created in the comments_controller.rb file, as they are not required for our web app. Add one new method called “create” as shown in the code below.
This simply creates a comment record in the “comments” table, which is related to a given post.
class CommentsController < ApplicationController
def create
@post = Post.find(params[:post_id])
@comment = @post.comments.create!(params[:comment])
redirect_to @post
end
end
Refresh the browser (make sure your server is still running at the command prompt).
Allow the User to Comment!
Now you can try to add a comment. Enter a comment and click “Add Comment”. The new comment should appear under the post as shown below.
Allow the User to Comment!
Summary
What have you Learnt?
You have learnt the basic concepts behind application design and translating the design into a working Rails web application. Having, at least, a basic understanding of application design is important when learning Rails and is the key to succeeding.
How can you improve the Blog?
What we covered in this tutorial was just enough to get the message across. There are plenty of things you could do to improve things.
Adding some CSS or using some AJAX to make things run a bit smoother are just a few suggestions.
What Next?
Try learning MVC, so you really understand the concepts behind it. Try to understand the advantages of Rails and MVC; this will motivate you to learn the framework. However, while reading up on the theory is good, you really need to just get stuck in and play with the framework.
Download and Install Rails at take your first steps towards more productive and enjoyable web development.