A guide to using Ahoy 2.0 on Ruby on Rails

Soham Dongargaonkar
2 min readApr 17, 2018

--

As a developer working on LinkHero, I have had a chance to dive deep into Ahoy and use it to track events, such as when someone visits your site or clicks a link on a page you shared. Here’s a guide to get it set up, and use Ahoy::Events and Ahoy::Visits to start tracking your data.

As a first step, include the gem in your gem in your Gemfile.

gem ‘ahoy_matey’

And run

bundle install

rails generate ahoy:install

rails db:migrate

This will create the Ahoy migrations and include Ahoy Events and Visits to your rails app.

The difference between an Event and a Visit is important. Visits hold data about a visitor, and Events hold data about the activities the visitors did on your web page. Needless to say, a single Visit will have many Events.

An important thing to note about Visits is that, if a person comes to your website, a Visit is created by default. It can be prevented by using

Ahoy.server_side_visits = :when_needed

in config/initializers/ahoy.rb. This will create Visits only when you need one for an Event. Also, Ahoy will create a new Visit for the same person if he visits your website after an interval of 4 hous. Thus, he will be treated as a new visitor even though his IP address, User Agent, referrer domain is the same. If you have a high traffic on your website, this can create a large number of unnecessary and repetitive records. To modify it, you can use

Ahoy.visit_duration = 24.hours

Let’s get down to tracking customised Events and retrieving them. An Event is tracked with

ahoy.track(“User clicked buy now!”, {title:”#{params[:product]}”}.to_json)

in your buy controller. This automatically creates a Visit if for some reason it doesn’t exist (this feature was added in Ahoy 2.0) and an Event, with the name “User clicked buy now!” and in the properties column, adds the JSON that we supplied. This event can be retrieved with

Ahoy::Event.where_properties(title: “your_product_here”)

But let’s say you wanted to find who visited your website page, that is, the corresponding Visits associated with this Event, because Visit contains some very useful information, such as referring domain, that is, the page that referred the user to your site. For this, you’d use a join of Visit and Events, since Events have the column “visit_id” in their schema definition. The query would then look something like:

@joined_visits = Visit.joins(:ahoy_events).where(:ahoy_events=>{:properties => {title: “your_title_here”}})

@grouped_visits = @joined_visits.group(:referring_domain).count()

And in your front end:

<%@grouped_visits.each do |referring_domain, count|%>

<%=referring_domain%>, <%=count%>

<%end%>

And that’s all. Events are highly flexible because of the properties JSON attribute in Events, that allows to create custom titles and attributes of your own. If there are any questions, I’ll be happy to answer in the comments below.

--

--