emersonthis emersonthis - 1 year ago 71
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 Source

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

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

  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: