When building web applications, sometimes you meet requirements to count page views in Rails to show visitors information about how many times
this page or post has been viewed. It sounds simple, but implementing a reliable hit counter for page views in Rails raises several essential questions:
- Should every request increase the counter?
- Should repeated visits from the same user count?
- How do you count unique users?
- How do you track page views for logged-in users?
- What should happen with anonymous visitors?
- Do you need Redis or an external analytics service?
- How can you display the number of views on a Rails page?
Tracking page views is especially useful for blogs, forums, knowledge bases, news portals, and documentation sites. Showing view counts on individual resources provides valuable insights into what content truly resonates with your audience.
How to count page views in Rails ?
A page view counter records visits to a particular page or resource. For example, imagine that your Rails application has
a Post model and you want to display views every time a visitor opens the post. The most
straightforward implementation is to increment a counter every time the controller action is executed using an SQL update like this:
def show
@post = Post.find(params[:id])
@post.increment!(:views_count)
end
This approach is extremely simple. However, it has an important limitation: when a visitor refreshes the page ten times, the counter increases by ten. That may not be what you want. For many applications, the more useful question is: How many unique visitors viewed this page? That requires storing information about the visitor rather than merely incrementing a counter.
Introducing the paulie_lombardo gem
To answer all the questions mentioned above, we will look at a lightweight solution using
the paulie_lombardogem, designed specifically to solve
the Ruby on Rails page view counter challenge. The approach is based on tracking page views
using ActiveRecord and your existing database, with no requirement for Redis, Memcached, or a separate analytics system.
By default, paulie_lombardo tracks unique views. This means that if a visitor opens a page multiple times across
different days, the view count will not increase. However, you can customize this timeframe by passing the interval option:
- default: Repeated visits will not increment the counter, regardless of how much time passes. It identifies the visitor by request_fingerprint, rails_session, or authenticated_user_id and decides whether to increment the view count.
- interval: :daily: Multiple visits on the same day count as a single view, but visiting again the next day will increment the counter. It identifies the visitor the same way as default, but with an additional calendar day check.
Step-by-step guide: How to count view on a post in Rails
Let's walk through how to set up paulie_lombardo in a fresh or existing Rails project.
Add the gem to your application's Gemfile:
gem "paulie_lombardo", "~> 1.0"
Then run bundle install in your terminal:
bundle install
The next step is to generate the necessary migration files to store view tracking records.
rails generate paulie_lombardo:install posts
The generator adds migrations for:
- creating
paulie_notestable - adding
paulie_notes_countcounter cache column on thepoststable
Then run:
rails db:migrate
Configure Post model
class Post < ApplicationRecord
has_paulie_notes
end
Then track the view from your controller action with paulie_note method:
class PostsController < ApplicationController
before_action :set_post, only: %i[ show edit update destroy ]
# GET /posts/1 or /posts/1.json
def show
paulie_note(@post)
end
end
That's it. When the show action is executed, Paulie records the visit.
Now you can display the number of views in your ERB template:
<article>
<h2><%= @post.title %></h2>
<span>Views: <%= @post.paulie_notes_count %></span>
</article>
In this example, we cover the default behavior of the gem, where repeated visits by the same request, session, or user do not continually
increase the counter. This gives you a complete hit counter for page views in Rails without implementing the tracking system manually.
What Else paulie_lombardo Can Do
Tracking daily page views
As mentioned above, Paulie supports a daily tracking interval. For this feature, you need to override the default behavior by
passing the option: has_paulie_notes interval: :daily. Now, the same visitor can generate a new counted view on a new calendar day. For example:
- October 1 -> 1 view
- October 1 -> repeated visits - no additional view
- October 2 -> 1 additional view
- October 3 -> 1 additional view
Displaying page views for static Rails pages
Not every page belongs to an ActiveRecord model. Sometimes you need to display page views for static Rails pages like: Landing, Home, About.
In this case, you don't have to create a dummy model simply because you want to count views for a page - PaulieLombardo can track those pages too. For example:
class PagesController < ApplicationController
def landing
# If you need to use the interval option for unique views per calendar day,
# replace the line below with: @page = paulie_note("landing", :daily)
@page = paulie_note("landing")
end
end
Use the @page.paulie_notes_count method to display the total number of views:
<h1>Static page</h1>
<p>Total views: <%= @page.paulie_notes_count %></p>
User identification
One of the useful features is that it can distinguish authenticated users when the application uses Warden.
When a request is processed, PaulieLombardo checks:
request.env["warden"]
If an authenticated user is available, the user's ID can be stored in the :user_id field.
This allows view uniqueness to be associated with the actual application user.
Final thoughts
Counting page views in Rails can be as simple or as complicated as your application requires.
If you only need a raw request counter, a single integer column may be enough.
If you need unique visitors, daily tracking, authenticated user identification, and access to individual view records, you need a little more structure.
That is the problem paulie_lombardo was created to solve.
It provides a small Ruby on Rails page view counter built around ActiveRecord, with support for unique tracking, daily intervals,
ActiveRecord models, static pages, and authenticated users.
To learn more, check out the source code, open a pull request, contribute, or star the project on:
GitHub: https://github.com/stadniklksndr/paulie_lombardo.
The gem is also available on RubyGems:
RubyGems: https://rubygems.org/gems/paulie_lombardo.