A Rails Blog In VS Code-Posts Tips&Tricks

How To Create A Blog in VS Code — Part IV — RailsSeries#Episode 06

J3
Jungletronics
7 min readJul 13, 2023

--

Let’s Create some Functionalities to work with Posts.

In this post:

You will:

Learn how make a custom migration;

Learn about Metrics: learn the basics of counting post and page views;

Learn about routes, dropdowns, and the like 👌️
Fig. 0: This post is a continuation of this one; This is a working code: 👉️rails_blog_v4

Let’s Get Started!

0#step — Download the last post here and prepare your vscode environment.

1#step — GoTo home.html.erb to set links to Blogs:

rails-blog-demo/app/views/pages/home.html.erb

<%= link_to 'Blog', posts_path, class: 'btn btn-primary' %>

2#step —Add Javascript Bootstrap 5; GoTo CDN and paste JS link code here:

rails-blog-demo/app/views/layouts/application.html.erb

head>

...

<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script>

...

</head>

3#step —GoTo _navbar.html.erb and adjust the dropdown menu:

rails-blog-demo/app/views/layouts/_navbar.html.erb

Because of this problem:

Fig. 1: The dropdown menu is cropped…

Add this line dropdown-menu-lg-end:

<ul class="dropdown-menu dropdown-menu-lg-end" aria-labelledby="navbarDropdown">

Now the problem is gone…

Fig. 2: The solution comes from this line: dropdown-menu-lg-end

4#step — Create a link to new post in the dropdown menu:

<a>Dropdown</a>
...
<ul ...>
<li><%= link_to "New Post", new_post_path , class: "dropdown-item" %></li>
...
</ul>
Fig. 3: New Post link looks good…

5#step — Link to Blog in Navbar too; GoTo

<ul>
...
<li class="nav-item">
<%= link_to "Blog", posts_path, class: 'nav-link' %>
</li>
...
</ul>
Fig. 4: Blog link on navbar. Pretty neat!

6#step — Let’s make a custom migration to create a new field in the Post table:

rails g migration add_views_to_posts views:integer

In Rails 7, the line rails g migration add_views_to_posts views:integer is a command used to generate a new migration file for adding a column called views to the posts table in your Rails application’s database schema.

The command rails g migration is short for rails generate migration and is used to create a new migration file. Migrations in Rails are a way to manage database schema changes over time.

The name of the migration file is generated automatically based on the provided attributes. In this case, add_views_to_posts suggests that the migration will add a column to the posts table.

The views:integer part is a generator argument that specifies the name of the column being added (views) and its data type (integer). In this case, the views column will be of type integer, which typically stores whole numbers.

After running this command and migrating the database, a new migration file will be created with the necessary instructions to add the views column to the posts table. You can then edit the generated migration file to define the specific changes you want to make to the database schema, such as adding the column and any associated indexes or constraints.

7#step — Editing the generated migration file (just add default: 0):

class AddViewsToPosts < ActiveRecord::Migration[7.0]
def change
add_column :posts, :views, :integer, default: 0
end
end

8#step — GoTo _post.html.erb type this:

<h6><%= pluralize(post.views, “view”)%> </h6>

See the whole file:

rails-blog-demo/app/views/posts/_post.html.erb

<div id="<%= dom_id post %>">
<p>
<strong>Title:</strong>
<%= post.title %>
<h6><%= pluralize(post.views, "view")%> </h6>
</p>
<p>
<strong>Body:</strong>
<%= post.body %>
</p>
</div>

The code <h6><%= pluralize(post.views, "view") %></h6> is an ERB (Embedded Ruby) code snippet commonly used in Rails views to display the number of views for a specific post.

Let’s break it down:

  • <h6>: This is an HTML tag, specifically an <h6> heading element, indicating that the following text should be displayed as a level 6 heading.
  • <%= %>: This is an ERB tag used to embed Ruby code into the view. Whatever code is placed between these tags will be executed and the result will be rendered in the view.
  • pluralize(post.views, "view"): This is a Rails helper method called pluralize. It takes two arguments: the number of views for the post object and the singular form of the word view.
  • post.views: Assuming post is an object representing a post, post.views retrieves the number of views for that post.
  • "view": This is the singular form of the word "view" that will be used in the pluralized method.

So, when this code is executed, it will display the number of views for a post, followed by the word view or views depending on the count. For example, if post.views returns 1, it will display 1 view, and if it returns a value greater than 1, it will display the plural form, such as 5 views. The resulting text will be wrapped in a <h6> heading element for styling purposes.

Because we put the views in our post partials so anywhere you render this post all of these changes are going to propagate throughout your application.

So there’s only a single point of change here.

So that’s really neat! 👌️

9#step — GoTo posts_controller.rb show method and type:

rails-blog-demo/app/controllers/posts_controller.rb

  # GET /posts/1 or /posts/1.json
def show
@post.update(views: @post.views + 1)
end

In Rails 7, the code @post.update(views: @post.views + 1) is used in a controller to update the views attribute of a @post object.

Let’s break it down:

  • @post: It refers to an instance variable that holds a specific post object.
  • @post.views: It retrieves the current value of the views attribute for the @post object.
  • @post.views + 1: It increments the current value of views by 1, effectively increasing the view count by 1.

The update method is a built-in ActiveRecord method in Rails that updates the attributes of an object in the database. It takes a hash of attribute-value pairs as an argument. In this case, the attribute being updated is views, and the new value is @post.views + 1.

By executing @post.update(views: @post.views + 1), the views attribute of the @post object is incremented by 1, and the change is persisted in the database. This code is commonly used when you want to track the number of views or any other kind of counter associated with a post or any other resource in your application.

This update() method is the same as:

views = @post.views +1
@post.views = views
@post.save

10#step — Now type:

rails db:migrate

And there you have it:

Fig. 5: Everything is working fine…the counting post is working!

But there is a problem here:

Apollo 13: ‘Houston, We’ve Had a Problem’

What happens if I go into a new post like I can do this even if I open up an incognito tab and go to slash post slash new?

You of course only want certain people to be able to create posts, I’d imagine…

So we’re going to have to create some user accounts.

This is going to use a gem called devise.

But this is subject to the next post…

That’s all folks!

In the next post, we will use devise

Bye for now!

👉️ rails_blog_v4

For your convenience:

rails g migration add_viewa_to_posts views:integer
rails db:migrate
rails s

git add -A
git commit -m ":sparkles: feat: add views to posts"
git push

git push heroku master
heroku db:migrate
heroku run rails db:migrate
heroku open

Related Posts:

00# Episode — RailsSeries — Installing Ruby on Rails Using ASDF — Why ASDF is Better Than RBENV for Rails Bootstrap App?

01# Episode — RailsSeries — How To Send Email In Rails 7? — User Registration and Onboarding.

02# Episode — RailsSeries — 14 Ruby Extensions 4 Vs Code — Based On This Deanin’s video.

03# Episode — RailsSeries — A Rails Blog In VS Code — Quick Start — How To Create A Blog in VS Code — Part I

04# Episode — RailsSeries — A Rails Blog In VS Code — Styling — How To Create A Blog in VS Code — Part II

05# Episode — RailsSeries — A Rails Blog In VS Code — Create Posts — How To Create A Blog in VS Code — Part III

06# Episode — RailsSeries — A Rails Blog In VS Code — Posts Tips&Tricks — How To Create A Blog in VS Code — Part IV (this one)

07# Episode — RailsSeries — A Rails Blog In VS Code — Devise — How To Create A Blog in VS Code — Part V

08# Episode — RailsSeries — A Rails Blog In VS Code — Add Comments to Post — How To Create A Blog in VS Code — Part VI

09# Episode — RailsSeries — Rails Blog In VS Code — Using Stimulus — How To Create A Blog in VS CodePart VII

10# Episode — RailsSeries — Rails Blog In VS Code — Noticed V1 — Notifications for your Ruby on Rails app — Part VIII

11# Episode — RailsSeries — Rails Blog In VS Code — Noticed V2 — Notifications for your Ruby on Rails app — Part IX

For v4 let’s Tag it all!

git tag -a rails_blog_v4 -m "Blog in Rails 7 - v1.0:  Go to  https://j3-rails-blog-demo-5a0a55d44e12.herokuapp.com/" -m "0- Set JavaScript to bootstrap head;" -m "1- make a custom migration;" -m "2- Metrics: learn the basics of counting post and page views;" -m "3- Modify routes, dropdowns, and the like." -m "4- Making adjustments to post controller show method ;" -m "5- Upload Rails 7 project to heroku." -m "Thank you for downloading this project 😍️" 

git push origin rails_blog_v4

--

--

J3
Jungletronics

😎 Gilberto Oliveira Jr | 🖥️ Computer Engineer | 🐍 Python | 🧩 C | 💎 Rails | 🤖 AI & IoT | ✍️