Build a Blog with Ruby on Rails

Following this GoRails playlist

[TOC]


Requirements:

Rails New

# create new project
rails new blog

# see it running
cd blog
rails server

Scaffold

bundle update
rails generate scaffold BlogPost title:string body:text
rails db:migrate

some more steps

authentication with devise

bundle add devise
rails generate devise:install
rails generate devise User
rails db:migrate

In the controller:

before_action :authenticate_user!, except: %i[index show]

Add some way for the user to login/logout/create an account. Example:

# layout/application.html.erb
if user_signed_in?
  button_to 'Log out', destroy_user_session_path, method: :delete
else
  link_to 'Login', new_user_session_path
  link_to 'Sign Up', new_user_registration_path
end

Also add a link to "Edit" if in a post owned by the user

TailwindCSS

bundle add tailwindcss-rails
rails tailwindcss:install

in application.html.erb:

<body class="prose mx-auto">

BlogPost Model

# generate a model for a blog post
rails generate model BlogPost title:string body:text
# it creates a migration and a model

# run the migration
rails db:migrate

# interact with the webapp via irb
rails console
# you can now perform CRUD operations with BlogPost
# for example, create a new blog post:
# BlogPost.create(title: 'Hello World', body: 'This is my very first blog post')
# try also these methods: update, destroy, find, all

# just for awareness, check BlogPost.model_name in the console

BlogPost Controller

config/routes.rb:

# ...
  root 'blog_posts#index'
# end

shell again:

# generate the controller
rails generate controller BlogPosts

index

<h1>Blog Posts</h1>
<ul>
  <% @blog_posts.each do |post| %>
    <li>
      <%= link_to post.title, post %>
    </li>
  <% end %>
<ul>

show

  1. edit routes.rb to add a route to show
  2. create show method in the controller
  3. create the show.html.erb file

app/controllers/blog_posts_controller.rb:

# ...
  def show
    @blog_post = BlogPost.find(params[:id])
  rescue ActiveRecord::RecordNotFound
    redirect_to root_path
  end
# ...

Also edit the index.html.erb:

  <h2>
    <%= link_to post.title, post %>
  </h2>

Also create the views for each action inside app/views/blog_posts.

new

app/views/blog_posts/new.html.erb:

<%= form_with mode: @blog_post do |form| %>
  <div>
    <%= form.label :title %>
    <%= form.text_field :title %>
  </div>
  <div>
    <%= form.label :body %>
    <%= form.text_area :body %>
  </div>
  <%= form.button %>
<% end %>

PAREI AQUI