Today, we're going to start building a fully-featured blog using Ruby on Rails 7 with Hotwire and Turbo. In this series of how-to blog posts, I'll walk you through the entire process of creating a beautiful, SEO-friendly blog that supports categories, tags, comments, rich text editing, image uploading, and more. We'll also discuss various deployment options, including AWS virtual machines and Docker containers.
Step 1: Setting up the Rails 7 application
First, let's make sure we have Rails 7 installed. Run the following command to install or update Rails:
gem install rails
Next, let's create a new Rails application with Hotwire and Turbo:
rails new my_blog --database=postgresql --skip-turbolinks -d postgresql --css bootstrap
Now, let's navigate to our new application directory and create the initial database:
cd my_blog rails db:create
To verify everything is set up correctly, start the Rails server:
rails server
You should see your brand new Rails application running at http://localhost:3000.
Step 2: Setting up the Post model and scaffold
Let's generate a scaffold for our Post model with the following attributes: title, body, category_id, and featured_image.
rails generate scaffold Post title:string body:text category_id:integer featured_image:integer rails db:migrate
Step 3: Setting up categories and tags
To create categories and tags, we'll need two additional models: Category and Tag. Let's generate them:
rails generate model Category name:string rails generate model Tag name:string rails db:migrate
We'll also need a PostTag join table to create a many-to-many relationship between Post and Tag. Generate the migration and migrate the database:
rails generate migration CreateJoinTablePostsTags posts tags rails db:migrate
In the Post model (app/models/post.rb), add the following associations:
class Post < ApplicationRecord belongs_to :category has_and_belongs_to_many :tags end
In the Category model (app/models/category.rb), add:
class Category < ApplicationRecord has_many :posts end
And in the Tag model (app/models/tag.rb), add:
class Tag < ApplicationRecord has_and_belongs_to_many :posts end
Now our models are ready to handle categories and tags.
In the next part of this series, we'll cover creating the frontend using Bootstrap, setting up a rich text editor, implementing ActiveStorage for image uploads, and adding a featured image to our blog posts.
Stay tuned for Part 2!