| Work | Research and Development (R&D) | Growth | Data and Analytics | How to add Google Analytics to Rails
How to add Google Analytics to Rails

Overview

In this guide we'll walk through how to add Google Analytics to your Rails application.

Create a Google Analytics account

Visit https://analytics.google.com and create an account. Create a "web" type property. Locate your property ID which should look similar to this UA-123456789-1.

Create a Google Tag Manager account

Visit https://tagmanager.google.com and create an account. Create a "web" type container. Create a New Tag, select "Google Analytics: Universal Analytics" Track Type: Page View, Google Analytics Settings: New Variable and add in your Google analytics property ID UA-123456789-1. Add a trigger for All Pages with type Page View. Save the Tag.

Create a separate trigger with type "Custom Event" and Event name "customPageView" which fires on All Custom Events, Save the Trigger.

Publish/Submit your container.

Add in tracking code

Create file /app_name/app/assets/javascripts/vendor/google_analytics.js

document.addEventListener('turbolinks:load', function(event) {
  if (typeof ga === 'function') {
    ga('set', 'location', event.data.url);
    return ga('send', 'pageview');
  }
});

Create file /app_name/app/views/partials/_track_analytics.html.haml and replace GTM_ID

- if Rails.env.production?
  :javascript
    (function(w,d,s,l,i){w[l]=w[l]||[];w[l].push({'gtm.start':
    new Date().getTime(),event:'gtm.js'});var f=d.getElementsByTagName(s)[0],
    j=d.createElement(s),dl=l!='dataLayer'?'&l='+l:'';j.async=true;j.src=
    'https://www.googletagmanager.com/gtm.js?id='+i+dl;f.parentNode.insertBefore(j,f);
    })(window,document,'script','dataLayer','GTM_ID');

Modify file /app_name/app/views/layouts/application.html.haml by rendering trackanalytics in the head tag and adding the google tag manager iframe to the body, remember to replace GTMID.

%html{:lang => "en-US"}
  %head
    ...
    = render '/partials/track_analytics'
  %body
    %noscript
      %iframe{:height => "0", :src => "https://www.googletagmanager.com/ns.html?id=GTM_ID", :style => "display:none;visibility:hidden", :width => "0"}

Test the implementation with Tag Assitant

Install Tag Assistant Google Chrome Extension. Find the icon for Tag Assistant to the right of the menu bar and press enable. Visit www.yourapp.com and you Tag Assistant should detect Google Tag Manager and Google Analytics.

Test the implementation with Google Analytics Real Time Overview

In a separate tab, open Google Analytics > Real Time > Overview.

In a separate tab, open www.your_website.com, switch back to Google Analytics Real Time Overview and you should see a new active user on the site.