Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Google analytics with rails 4

I am having a bit of difficulty implementing google analytics to my rails 4 project. I included the tracking code to the bottom of my layouts file and have even tried to remove turbolinks as suggested here however i google is still unable to detect this tracking cookie. Any ideas ?

like image 938
Joshua Avatar asked Sep 05 '13 09:09

Joshua


2 Answers

I set up Google Analytics a few days before..

1.) The Turbolink Workaround

With Turbolinks, the Google Analytics JavaScript library is not sufficient to record a page visit for every page update.

The workaround should be loaded on every page and it can be included as an application-wide asset (it will load before Turbolinks).

Add the file app/assets/javascripts/analytics.js.coffee to include the Turbolinks workaround:

app/assets/javascripts/analytics.js  // Coffee $(document).on 'page:change', ->  if window._gaq?   _gaq.push ['_trackPageview']  else if window.pageTracker?   pageTracker._trackPageview()  // Javascript $(document).on('page:change', function() {  if (window._gaq != null) {   return _gaq.push(['_trackPageview']);  } else if (window.pageTracker != null) {   return pageTracker._trackPageview();  } }); 

2.) Create a Footer Partial

Just create a a Partial into app/views/layouts -> _footer.html.erb

Then Call your Partial on your application.html.erb -> <%= render 'layouts/footer' %>

Insert into your Footer the Analytics Track Code:

<script>   (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-XXXXXXX-XX', 'herokuapp.com');   ga('send', 'pageview');  </script> 

You must replace UA-XXXXXXX-XX with your tracking ID, and herokuapp.com with your Domain if you have any.

like image 161
Mini John Avatar answered Oct 02 '22 23:10

Mini John


Here is code without using coffeescript:

app/assets/javascripts/analytics.js  $(document).on('page:change', function() {  if (window._gaq != null) {   return _gaq.push(['_trackPageview']);  } else if (window.pageTracker != null) {   return pageTracker._trackPageview();  } }); 
like image 42
poerror Avatar answered Oct 02 '22 23:10

poerror