Google Analytics Setup for Rails 5.2

Signup for Google Analytics and get the javascript code that contains the UA-XXXXXXX for your site. Turbolinks makes the setup bit more involved. Copy the javascript code within the head section of the layout file.

  <head>
    <title>DeveloperTask</title>
    <%= csrf_meta_tags %>
    <%= csp_meta_tag %>

    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>

    <% if Rails.env.production? %>
      <!-- Global site tag (gtag.js) - Google Analytics -->
      <script async src="https://www.googletagmanager.com/gtag/js?id=UA-134291848-1"></script>
      <script>
        window.dataLayer = window.dataLayer || [];
        function gtag(){dataLayer.push(arguments);}
        gtag('js', new Date());

        gtag('config', 'UA-134291848-1');
      </script>    
    <% end %>

    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>
  </head>

Note: Google analytics must be before the javascript include tag. Create a javascript file in app/assets/javascripts/google_analytics.js for triggering the analytics whenever turbolinks is loaded.

document.addEventListener('turbolinks:load', function(event) {
  if (typeof gtag === 'function') {
    gtag('config', 'UA-134291848-1', {
      'page_location': event.data.url
    })
  }
})

You will now be able to track all pages including the pages that are loaded using Turbolinks.

Reference

Google Analytics gtag setup for Rails 5.2


Related Articles


Ace the Technical Interview

  • Easily find the gaps in your knowledge
  • Get customized lessons based on where you are
  • Take consistent action everyday
  • Builtin accountability to keep you on track
  • You will solve bigger problems over time
  • Get the job of your dreams

Take the 30 Day Coding Skills Challenge

Gain confidence to attend the interview

No spam ever. Unsubscribe anytime.