Last Updated: August 08, 2018
·
2.842K
· usiegj00

Track visitors on Ruby on Rails (Ahoy gem)

Use the Ahoy gem (from Instacart). One line install:

Gemfile

# Track visit/event
gem 'ahoy_matey

Shell

bundle install
rails generate ahoy:install
rails db:migrate

app/controllers/application_controller.rb

after_action :track_action
# track events with ahoy_matey gem.
def track_action
ahoy.track "Viewed #{controller_name}##{action_name}", request.filtered_parameters
end

app/models/user.rb

# Add these
has_many :visits, class_name: "Ahoy::Visit"
has_many :events, class_name: "Ahoy::Event"

app/models/ahoy/event.rb

class Ahoy::Event < ApplicationRecord
  include Ahoy::QueryMethods
  self.table_name = "ahoy_events"
  belongs_to :visit
  belongs_to :user, optional: true
end

app/models/ahoy/visit.rb

class Ahoy::Visit < ApplicationRecord
  self.table_name = "ahoy_visits"
   has_many :events, class_name: "Ahoy::Event"
  belongs_to :user, optional: true
end

config/initializers/ahoy.rb

class Ahoy::Store < Ahoy::DatabaseStore
end
 # set to true for JavaScript tracking
Ahoy.api = false
 # better user agent parsing
Ahoy.user_agent_parser = :device_detector
 # Get the bots and know when they index you...
Ahoy.track_bots = true 

You now have user.visits.count, user.events.where(name: 'Viewed dashboard#show').count and more.