Having a view counter is a common thing when it comes to blog posts, tutorials, videos, etc... I wanted to have a view counter for a simple blog post app. I did some quick googling and found out about a gem called punching_bag. It is a very easy gem to use, I will be saying that a lot. Let's get started on showing you how to have a simple view counter for your rails application.
Installing this gem is very easy to do. It all starts with you adding the gem to your gemfile:
After you have the gem in your gemfile you will need to run three commands in your terminal:
To start off, you need to run
bundle install as usual. After you run bundle you need to run the generator for punching_bag:
rails g punching_bag
This will generate a table in your database called punches, which means you need to run
Once you got your database migrated, go into your Post Model and add this line of code:
Adding this will allow you to get the amount of hits/views on your posts. One last step, and that is to go into your PostController under the show method and have a punch with a request like so:
Congrats you have successfully installed punching_bag and configured it to work with your views. Sweet, let’s add a view counter to your views.
Using the gem in your views is very simple as well. To be honest, using the gem is very simple. For you to see a view counter in your views you need to call the hits like so:
That’s it you can now see how many views a Post has. That’s it, simple right? If you want to have your index for the posts to show the most viewed post at the top, that would be in your controller under the index method:
@posts = Post.most_hit
Now on your index posts page you can see that the post with the most views will be at the top. It’s like adding a scope but the punching bag gem already does that for you.
The punching bag gem is easy to use and works like a charm. Personally, using this gem is the best way to show views. I hope this helped you for your application. If you need any more information about the gem please visit the github link, Punching Bag.