Madduck
Madduck

Reputation: 37

Cant get google analytics working on rails project

Currently I'm using rails 5 and have been looking for a method of implementing google analytics in my application with turbolinks. Every site I go to says something different, and I've gone through loads of SO questions and none of them seem to work or are outdated.

Here's a shorter list of the methods I've tried:

https://medium.com/weareevermore/how-to-add-google-analytics-tracking-that-works-with-turbolinks-c5023610846d

http://nithinbekal.com/posts/turbolinks-google-analytics/

Rails 4 turbolinks with Google Analytics

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

I really thought that last one was gonna be most promising ¯\_(ツ)_/¯

So my question is what is the most updated method of integrating google analytics into a rails application?

Upvotes: 0

Views: 704

Answers (1)

jdgray
jdgray

Reputation: 1983

I ran into an issue before with Rails 5 and Turbolinks and came across this issue for help.

It looks like you have things working with rack-tracker (based on ekremkaraca's comment). If you don't want to use a dependency you can set up Google Analytics with fairly minimal code using a partial and javascript snippet. I have a few apps configured this way:

app/assets/javascripts/google_analytics.js

document.addEventListener('turbolinks:load', function(event) {
  if (typeof ga === 'function') {
    ga('set', 'location', event.data.url);
    ga('send', 'pageview');
  }
});

app/views/layouts/_ga.html.haml (Using haml and not erb in this example)

:javascript
  (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', 'YOUR_GA_CODE_HERE');

app/views/layouts/application.html.haml (Include the _ga partial in the head)

!!!
%html
  %head
    = stylesheet_link_tag    'application', media: 'all'
    = javascript_include_tag 'application'

    = render 'layouts/ga'
  %body
    = yield

app/assets/javascripts/application.js

...
//= require google_analytics

Upvotes: 2

Related Questions