Technology

How to Create a Blog from Scratch Using Ruby on Rails

One of the main advantages of Ruby on Rails is that it makes web development a breeze. It’s a web framework, so Ruby on Rails provides pre-built pieces and code that you can combine or modify. 

Consequently, you won’t need to code anything from scratch. Moreover, this web framework allows you to build web apps by handling both the back end and the front end. 

But this doesn’t mean you can jump in on Ruby on Rails as a fresher and become a master within minutes. It still has a bit of a learning curve. 

Sure, if you have the budget, you might be better off by working with the best Ruby on Rails development companies you can find. But still, there’s no harm in knowing a thing or two yourself.

It’s best to start by taking things easy. Creating a basic blog is a great way to get the hang of things and understand the fundamental concepts behind these web frameworks. 

So, let’s take a look at how you can build one yourself. 

  • Understanding The Key Elements

Let’s talk about MVC. MVC stands for Model-View-Controller. This architectural pattern allows you to easily insert a piece of code in certain parts of your web app. 

The model is where you set specific classes for the data your web app will use and store. This element will interact with the database to store and retrieve data. 

The view returns HTML so the web app can be seen on the users’ browsers. 

Lastly, the controller is the middle man between the view and the model. 

In other words, the controller is responsible for interacting with the model to store and fetch data and then passing that data down to the view. 

  • Starting Out

For starters, you’ll need to have the following software installed: 

  • Ruby
  • Rails Framework
  • A Web Server
  • A Database System

Although we won’t go through the installation process, you can check out this guide. It will show you everything you need to do to have Ruby installed on your machine. 

To verify whether you’ve installed the software correctly, you can insert the following commands in your command prompt: 

rails –version # minimum version 7.02.3

ruby –version # minimum version 3.1.0  

If you receive the same version numbers, you’re up to date and ready to go. 

  • Creating a Project

Next up, you’ve got to create a project. This is a folder structure that will store all of the files related to your web app. To do this, type in the following command in the command prompt: 

> rails rubyblog -d MySQL

In this case, we’ll use MySQL as our database management system. You can use other DBMSs like SQLite or PostgreSQL, for instance. 

This line of code will create a project named rubyblog. This project contains multiple folders like app, bin, config, DB, public, etc. 

There are a few subfolders you need to keep an eye on, more specifically: 

  • app\controllers\ – contains Ruby files
  • app\helpers\ – contains helper files that define logic
  • app\models\ – contains model files with functionality from ActiveRecord
  • public\images\ – contains images files that are used on your site
  • public\javascript\ – contains javascript files used on your site
  • public\stylesheets\ – contains CSS files used on your site
  • config\database.yml – contains info about the DBMS provider and authentication details
  • config\routes.rb – you can configure how you’ll route HTTP requests
  • Creating Post Models

Next up, you’ll need to create post models. These will contain all the necessary elements of your blog posts. Our post will include the following elements: Content and Comments to keep things simple.

That said, you’ll need to create a model for each one of these elements. But before that, you’ll have to understand how these models will relate to each other. 

There are multiple types of relationships in Rails. The most common ones are One-to-One, One-to-Many, and Many-to-Many. 

So, what are the relationships between your models?  

Given that a blog post can have multiple comments, we can give the Content and Comments models a One-to-Many relationship. 

  • Building The Scaffolding

You can use scaffolding to quickly generate a controller, model, and multiple views with one simple line of code. 

Let’s start by creating the scaffolding for our Content model: 

> ruby script/generate scaffold content name:string body:text

This line of code will create multiple files. More specifically, it will create a model named content.rb and a controller name content_controller.rb. 

Moreover, a sub-folder will appear in the views folder named content. This sub-folder will contain the following files: show.html.erb, edit.html.erb, and index.html.erb. 

The same thing goes when generating the models for other elements. 

Next is the scaffolding for our Comments 

> ruby script/generate scaffold comments name:string body:text 

  • Linking The Models

After generating the models, it’s time to assign the relationships we discussed earlier. 

First off, we’ll head over to the content.rb file:

class Content < ActiveRecord::Base

 has_many :comments

end

Then there are the comments.rb file:

class Comments < ActiveRecord::Base

 belongs_to :Content

end

After linking the models, you’ll need to create tables and a database that will contain the information about comments and posts. 

In terms of creating the database, you’ll need to head over to the config\database.yml file and add the password and username. You can do this by typing the following code: 

development:

 adapter: mysql

 encoding: utf8

 reconnect: false

 database: rubyblog_development

 pool: 5

 username: root 

 password: rootpassword

 host: localhost

Next up, you’ll need to insert a rake command in the command prompt to create the database. It should look like this: 

 > cd rubyblog

 > rake db:create

  • Migrating The Database

The next step is migrating the database. In short, this is the process of changing the state of your database. More specifically, you can create or remove tables or add and delete fields.  

As mentioned earlier, running the scaffold command will generate multiple files. Some of the created files are migration files located in the db\migrate folder, which you’ll use to generate tables for your Content and Comments models. 

You’ll need to run the > rake db:migrate command to do this.  

By now, you should have a barebones version of your blog. If you’d like to check it out, you’ll first need to launch Rails’ built-in web server. To do this, run this command: > ruby script/server.

All that’s left for you is to head over to http://localhost:3000/ on your web browser and see how things look.

  • Finishing Up The Blog

First off, you’ll need to set up your homepage. You can direct users to the root URL, http://localhost:3000/. But before that, you’ll have to delete the public/index.html file. 

The next step is creating a route in the config\routes.rb file. You can open this file using your editor and add this command at the end of the code: 

ActionController::Routing::Routes.draw do |map|

 map.resources :comments

 map.resources :content

 map.connect ‘:controller/:action/:id’

 map.connect ‘:controller/:action/:id.:format’

 map.root :controller => “content”

end

Now it’s time to add a little functionality to your blog. More specifically, you’ll need to give users the ability to post comments on your blog. To do this, head back to the routes.rb file and modify it accordingly:  

ActionController::Routing::Routes.draw do |map|

 map.resources :content, :has_many => :comments

 map.connect ‘:controller/:action/:id’

 map.connect ‘:controller/:action/:id.:format’

 map.root :controller => “content”

end

As you can see, we got rid of the map.resources :comments line, and integrated it into the map.resources :content section of the code. By adding the has_many, we allow the content to display multiple comments. 

Next, you’ll need to modify the view to render the content along with the comments. Moreover, you’ll need to enable users to post these comments. 

This is done by heading to the views/posts/show.html.erb file and modifying it. In other words, the code should look like this in Ruby on Rails: 

<p>

 <b>Title:</b>

 <%=h @content.title %>

</p>

<p>

 <b>Body:</b>

 <%=h @content.body %>

</p>

<h2>Comments</h2>

<% @content.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 [@content, 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 %>

All that’s left to do is go to the comments_controller.rb file and remove all the automatically generated methods, as they are redundant. After deleting them, you’ll need to add a new method to create a record of comments in the “comments” table.  

This table is tied to any post. This new method is named “create,” and you can add it using the following code. 

class CommentsController < ApplicationController

 def create

 @content = Content.find(params[:post_id])

 @comment = @content.comments.create!(params[:comment])

 redirect_to @content

 end

end

Moving forward, you can refresh the browser, and you’ll see the changes you’ve made. You should now be able to write a new comment and post it beneath the content. 

  • Final Words

And that’s it! You’re now up to speed with the basics of Ruby on Rails. Sure, there is still plenty of stuff to learn about, but the information shared in this article should be enough to get you going. 

Author bio:

Tomas is a digital marketing specialist and a freelance blogger. His work is focusing on new web tech trends and digital voice distribution across different channels.

Finwd Digital Agency

Haris Tyson

Recent Posts

Spotify DNA: What Is It And How It Works?

Our habits always have a pattern. Be it related to sleeping hours, working, listening to…

3 months ago

Instanavigation Details And Benefits

On the social site Instagram, users can update their status as stories, which they can…

3 months ago

Perks of Outsourcing Digital Marketing for Businesses

Because of various upgrades in technology, things have moved pretty fast and the competition level…

3 months ago

Impact Of Artificial Intelligence On Our Future

Ever since the term ‘Artificial Intelligence’ was coined, people desperately wanted to know what it…

3 months ago

Is iPhone 16 Pro The Best And Most Affordable Pro Model Ever?

In recent days, there has been a lot of discussion regarding the iPhone 16 Pro…

3 months ago

Will iPhone 16 Raise The Bar With Apple Intelligence?

With a boatload of new additions, like Apple Intelligence and a dedicated Camera 'Button', the…

3 months ago