emersonthis emersonthis - 2 months ago 16
Ruby Question

Rails 4 turbolinks with Google Analytics

I'm wondering what is the best way to implement Google Analytics tracking code along with the turbo linking in Rails 4. Will the normal snippet work? I've also seen a gems for this but I'm not sure what it does.

Answer

I think a better ideea is to use the new Universal Analytics (from analytics.js file). All the code above is using the standard analytics ( from ga.js file).

Universal Analytics Solution

  (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', "#{GA_UA}", "#{GA_URL}");
  ga('send', 'pageview');

And then when you wanna send an event for example, you can use

<script> ga('send', "event", "#{category}", "#{action}", "#{label}", "#{count}"); </script>

Be careful to render this code in the body, and not in the head. Turbo-links only replaces the body.

And also be careful:

1) The GA_URL needs to match your pages's url

2) The Events show up in real time, but in the events tab, they only appear after 24h +

3) Your account's property need to be 'Universal' for this solution to work

Universal Analytics docs:

https://support.google.com/analytics/answer/2790010?hl=en&ref_topic=2790009