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 ?

Joshua
  • 805
  • 1
  • 8
  • 18
  • 1
    Try installing the Omnibug Firebug plugin for Firefox. If you have GATC installed on a page this plugin will easily show you the requests made to Google. https://addons.mozilla.org/En-us/firefox/addon/omnibug/. If you see nothing being sent, then check your JavaScript error console in your browser as you may have JS errors. – crmpicco Sep 05 '13 at 10:44
  • http://readysteadycode.com/howto-access-the-google-analytics-api-with-ruby – maurymmarques Jun 09 '16 at 21:40

6 Answers6

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.

Mini John
  • 7,855
  • 9
  • 59
  • 108
  • 1
    Cruising through some of your Rails answers... Nice work TMJ :) – zx81 Jun 06 '14 at 05:05
  • Note that this example comes straight from [Google's advanced configuration page](https://developers.google.com/analytics/devguides/collection/analyticsjs/advanced). – Caleb Jun 14 '14 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 Jun 14 '14 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 Jul 14 '14 at 19:31
  • This solution worked for me. One thing that repeatedly threw me off: the "Status: Tracking Not Installed" message in the Google Analytics dashboard did not immediately go away. However, I was able to verify that the tracking code was working by viewing the Real Time: Overview dashboard and navigating my website. – wrydere Nov 18 '14 at 05:14
  • Issue popping up where this method works in dev but not in prod. Is there something I should be checking about default Rails 4 prod environment that might break this setup? – Laurent May 05 '15 at 16:10
  • Are these 2 standalone solution or 2 steps of 1 solution? I'm kind confused. – ZK Zhao Oct 01 '15 at 07:37
  • 1
    Hey @cqcn1991, those are 2 steps for getting Google Analytics to work with your Rails App. – Mini John Oct 01 '15 at 08:15
  • where exactly in the application.html.erb should I place the partial? – Rashed Al-Julaibi Mar 24 '16 at 11:51
  • @RashedAl-Julaibi just above the closing

    tag.

    – Joe Eifert Aug 20 '17 at 09:55
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();
 }
});
poerror
  • 334
  • 3
  • 8
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.

Mr Lister
  • 45,515
  • 15
  • 108
  • 150
perezdr
  • 63
  • 1
  • 7
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()
Joshua Dance
  • 8,847
  • 4
  • 67
  • 72
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

Tarun Garg
  • 717
  • 6
  • 19
  • 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?](http://stackoverflow.com/help/deleted-answers) – bummi Jan 29 '15 at 10:32
  • Ok. I will take care it – Tarun Garg Jan 29 '15 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');
});
Vedant Agarwala
  • 18,146
  • 4
  • 66
  • 89