Using Google Analytics with Rails

Everyone loves Google Analytics. Here's how to implement tracking on a Rails site.

Tags: Google Analytics, Ruby on Rails

Back to Blogs

So after a great deal of spelunking through outdated blog posts, here's the best way I've found so far to implement GA on a Rails site. As documented in many, many Stack Overflow posts (like this guy, from whom I eventually found the answer that works best in my experience) Turbolinks is a huge issue with Google Analytics implementation. I have started disabling and removing Turbolinks, but this code should work whether or not Turbolinks is in your app.

First, this code goes inside the assets/javascripts folder in an appropriately-named analytics.js file:

$(document).on('page:change', function() {
 if (window._gaq != null) {
  return _gaq.push(['_trackPageview']);
 } else if (window.pageTracker != null) {
  return pageTracker._trackPageview();
 }
});

Next, this guy goes in <script> tags right before your closing </body> tag on your application.html.erb. As always, don't forget to replace the GA code with your actual one from Google and the "sitenamehere" with your url. Duh.

(function(i,s,o,g,r,a,m){i['GoogleAnalyticsObject']=r;i[r]=i[r]||function(){
  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),
  m=s.getElementsByTagName(o)[0];a.async=1;a.src=g;m.parentNode.insertBefore(a,m)
})(window,document,'script','//www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXXXXX-1', 'sitenamehere.com');
ga('send', 'pageview');

Back to Blogs