Build a Blog with Ruby on Rails
Following this GoRails playlist
Question
Should I try this to style this project?
Requirements:
- Ruby 3.2
- Rails 7.0.4
# create new project
rails new blog
# see it running
cd blog
rails server
# generate a model for a blog post
rails generate model BlogPost title:string body:text
# it creates a migration and a model
# generate the controller
rails generate controller BlogPosts
# 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
config/routes.rb
:
# ...
root 'blog_posts#index'
# end
app/controllers/blog_posts_controller.rb
:
# ...
def show
@blog_post = BlogPost.find(params[:id])
rescue ActiveRecord::RecordNotFound
redirect_to root_path
end
# ...
Also create the views for each action inside app/views/blog_posts
.
app/views/blog_posts/index.html.erb
:
# ...
<% @blog_posts.each do |blog_post| %>
<h2><%= link_to blog_post.title, blog_post %></h2>
<%= blog_post.body %>
<% end %>
Note
In this snipped:
link_to blog_post.title, blog_post
The final blog_post
is actually an alias for
"blog_posts/#{blog_post.id}"
This is Ruby magic! 🪄
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 %>