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.

  (i[r].q=i[r].q||[]).push(arguments)},i[r].l=1*new Date();a=s.createElement(o),

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

Back to Blogs