38

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 ?

2

6 Answers 6

79

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.

10
  • 1
    Cruising through some of your Rails answers... Nice work TMJ :)
    – zx81
    Commented Jun 6, 2014 at 5:05
  • Note that this example comes straight from Google's advanced configuration page.
    – Caleb
    Commented Jun 14, 2014 at 13:58
  • 1
    Actually not at all. The Track code is provided when setting up a new Site and the Turbolink Workaround is from another Example.
    – Mini John
    Commented Jun 14, 2014 at 14:17
  • Not sure what I'm missing but G.Analytics is still thinking I'm reloading my home page when I navigate to another page using TurboLinks
    – bobomoreno
    Commented Jul 14, 2014 at 19:31
  • 1
    Hey @cqcn1991, those are 2 steps for getting Google Analytics to work with your Rails App.
    – Mini John
    Commented Oct 1, 2015 at 8:15
12

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();
 }
});
3

I used this gem and was very easy to set up. No extra .js file creation. Rails 3 helpers to manage google analytics tracking. Mostly intended for small to medium websites.

Just install the gem:

gem 'google-analytics-rails', '1.1.0'

Then run:

bundle install

Finally, this goes @ the production environment configuration:

Production only config/environments/production.rb:

# replace this with your tracker code
GA.tracker = "UA-112233-4"

app/views/layout/application.html.erb, in the <head> tag :

<%= analytics_init if GoogleAnalytics.valid_tracker? %>

I saw results immediately after pushing to Heroku.

2

I removed Turbolinks, and used the RailsProjects script, provided here:

http://railsapps.github.io/rails-google-analytics.html

Worked for me no problems. It detected it, and after a little while I could see the real time users so I know it is working.

Edit: The script appears to support Turbolinks on or off which is great.

# If Turbolinks is supported, set up a callback to track pageviews on page:change.
    # If it isn't supported, just track the pageview now.
    if typeof Turbolinks isnt 'undefined' and Turbolinks.supported
      document.addEventListener "page:change", (->
        GoogleAnalytics.trackPageview()
      ), true
    else
      GoogleAnalytics.trackPageview()
1

I was facing some problem in adding the GA with turbolinks so I referred some blogs and answers on stackoverflow and wrote a small blog on this. Please refer to this link http://tarungarg402.blogspot.in/2015/01/google-analyicts-wth-rails.html

2
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. Why and how are some answers deleted?
    – bummi
    Commented Jan 29, 2015 at 10:32
  • Ok. I will take care it
    – Tarun Garg
    Commented Jan 29, 2015 at 13:03
0

I use this in my rails app. I just put this in my application.js.erb

// GA racking code
(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','https://www.google-analytics.com/analytics.js','ga');

ga('create', 'UA-XXXXX-<%= Rails.env.production? ? '1' : '2' %>', 'auto');
// I have 2 GA properties- one for debug and another for production

// accommodate Turbolinks and track page views
$(document).on('ready page:change', function() {
    ga('send', 'pageview');
});

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.