Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 37 ยท Projects and Practice

Project: Build a Blog with Rails

Build a complete Rails blog: models, routes, controllers, views, comments, authentication, tests and deployment steps. Includes a runnable Ruby stand-in of the domain model, scopes and validations.

Time to put the whole course together. In this project you design a small blog with posts, comments, and an admin who can write: the "hello world" of every web framework, but done the Rails way, with validations, associations, authentication, tests and a deployment plan.

Rails cannot run on the site's Ruby runner, so the Rails code in each step is read-only: type it into a real app (rails new blog) to run it. To make the thinking part hands-on, the middle of the lesson has a runnable plain-Ruby model of the domain: it shows the validations, the scopes and the rules you will implement in Active Record. It is a stand-in, not Rails.

What we are building

  • Visitors read published posts and leave comments.
  • An admin signs in, creates, edits, publishes and deletes posts.
  • Posts have a title, body, slug and a publish date; comments need a name and a body.
  • URLs look like /posts/hello-rails.
flowchart LR
  V["Visitor"] --> I["GET /posts<br/>index"]
  V --> S["GET /posts/:slug<br/>show"]
  V --> C["POST /posts/:slug/comments"]
  A["Admin"] --> L["POST /session<br/>login"]
  A --> M["/admin/posts<br/>create, edit, publish, delete"]

The routes and who may use them.

Step 1: create the app and the models

SH
rails new blog --database=sqlite3
cd blog
bin/rails generate model Post title:string slug:string:uniq body:text published_at:datetime
bin/rails generate model Comment post:references name:string body:text
bin/rails generate model User email:string:uniq password_digest:string
bin/rails db:migrate

Use the lessons on migrations and associations for the details. Then fill in the models:

Ruby
class Post < ApplicationRecord
  has_many :comments, dependent: :destroy

  before_validation :build_slug, if: -> { slug.blank? && title.present? }

  validates :title, presence: true, length: { maximum: 120 }
  validates :body,  presence: true
  validates :slug,  presence: true, uniqueness: true

  scope :published, -> { where.not(published_at: nil).where(published_at: ..Time.current) }
  scope :recent,    -> { order(published_at: :desc) }

  def to_param = slug

  private

  def build_slug
    self.slug = title.parameterize
  end
end

class Comment < ApplicationRecord
  belongs_to :post
  validates :name, :body, presence: true
  validates :body, length: { maximum: 1000 }
end

class User < ApplicationRecord
  has_secure_password
  normalizes :email, with: ->(e) { e.strip.downcase }
end

to_param makes post_path(post) produce /posts/hello-rails instead of /posts/3. In controllers you then look posts up with Post.published.find_by!(slug: params[:id]).

Step 2: a runnable model of the rules

Before writing controllers, test your rules in plain Ruby. This stand-in implements the slug, validations and published scope so you can check edge cases quickly. Change the data and watch what happens.

Ruby Stand-in: Post, Comment, slug and scopes in plain Ruby

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with gets), it gets the next line from this box.

Check the output against your intent: the draft is saved but not published, the duplicate slug is rejected, and the blank post lists its errors. These are the same rules that validates and scope give you in Active Record.

Step 3: routes and controllers

Ruby
# config/routes.rb
Rails.application.routes.draw do
  root "posts#index"
  resources :posts, only: %i[index show] do
    resources :comments, only: :create
  end
  resource :session, only: %i[new create destroy]
  namespace :admin do
    resources :posts
  end
end
Ruby
class PostsController < ApplicationController
  def index
    @posts = Post.published.recent.includes(:comments).page(params[:page])   # page needs a gem such as pagy
  end

  def show
    @post    = Post.published.find_by!(slug: params[:id])
    @comment = Comment.new
  end
end

class CommentsController < ApplicationController
  def create
    @post    = Post.published.find_by!(slug: params[:post_id])
    @comment = @post.comments.build(comment_params)
    if @comment.save
      redirect_to post_path(@post), notice: "Thanks for your comment"
    else
      render "posts/show", status: :unprocessable_entity
    end
  end

  private

  def comment_params = params.expect(comment: %i[name body])
end

class Admin::BaseController < ApplicationController
  before_action :require_admin
  # require_admin redirects to the login page unless session[:user_id] belongs to a user
end

class Admin::PostsController < Admin::BaseController
  def create
    @post = Post.new(post_params)
    if @post.save
      redirect_to admin_posts_path, notice: "Post saved"
    else
      render :new, status: :unprocessable_entity
    end
  end
  # index, edit, update, destroy follow the standard resource pattern
  private
  def post_params = params.expect(post: %i[title body published_at])
end

See resourceful routes and strong parameters if any line is unfamiliar.

Step 4: views

ERB
<%# app/views/posts/show.html.erb %>
<article>
  <h1><%= @post.title %></h1>
  <p class="meta"><%= l @post.published_at, format: :long %></p>
  <%= simple_format h(@post.body) %>
</article>

<h2><%= pluralize(@post.comments.size, "comment") %></h2>
<%= render @post.comments %>

<%= render "comments/form", post: @post, comment: @comment %>
ERB
<%# app/views/comments/_form.html.erb %>
<%= form_with model: [post, comment] do |f| %>
  <% if comment.errors.any? %>
    <ul class="errors"><% comment.errors.full_messages.each do |m| %><li><%= m %></li><% end %></ul>
  <% end %>
  <%= f.text_field :name, placeholder: "Your name", required: true %>
  <%= f.text_area :body, rows: 4 %>
  <%= f.submit "Post comment" %>
<% end %>

Because <%= %> escapes HTML, a comment containing <script> is displayed as text. Never use raw or html_safe on user input.

Step 5: protect it and test it

  • Admin controllers inherit a before_action guard, as in authentication; log in with authenticate_by and reset_session.
  • Add rate_limit to: 5, within: 1.minute, only: :create to the comments controller so bots cannot flood you.
  • Write model tests for slug and validation, and an integration test for "visitor posts a comment", following testing with Minitest and integration tests:
Ruby
test "visitor can comment on a published post" do
  post = posts(:published)
  assert_difference "post.comments.count", 1 do
    post post_comments_path(post), params: { comment: { name: "Ana", body: "Great" } }
  end
  assert_redirected_to post_path(post)
end

Step 6: ship it

Follow the deployment lesson: set credentials, precompile assets, run migrations, deploy with Kamal or a platform, and check /up. Create the first admin with bin/rails console (User.create!(email:, password:)), never with a public sign-up form.

Stretch goals

  1. Tags with a many-to-many association (many-to-many).
  2. Markdown rendering with a sanitizing gem.
  3. Comment moderation: an approved boolean and an admin queue.
  4. An Atom feed at /posts.atom with respond_to.
  5. Email the author with a mailer when a comment arrives (mailers).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does defining to_param as the slug change?

    Rails calls to_param when building paths, so posts get /posts/hello-rails instead of /posts/3.
  2. 2. Why load posts with Post.published.find_by!(slug: ...) in the public controller?

    Scoping to published prevents drafts leaking, and find_by! raises RecordNotFound, which Rails turns into a 404.
  3. 3. Where should the first admin account come from?

    A blog with one author should not let strangers create privileged accounts.
  4. 4. A comment contains <script>. What keeps it from running?

    Output in <%= %> is HTML-escaped, so the tag is shown as text. Avoid raw and html_safe on user input.

Summary

  • Design first: pages, who may do what, and the models with their validations.
  • Use to_param, scopes (published, recent), nested routes and an Admin namespace guarded by a before_action.
  • Rely on escaping in ERB, strong parameters, rate limits and tests.
  • Deploy with credentials, migrations and a health check, then extend with tags, moderation and feeds.

Next: Rails practice and review