简体   繁体   中英

Rails 5: How can I get Google Analytics to work?

I tried to install google analytics on a Rails 5 website adding the Google Analytics Tracking Script created by Jonathon Wolfe and provided on Nick Reed's Turbolinks Compatibility site.

  • I replaced UA-XXXXXXX-XX with my Google Analytics tracking ID
  • the file app/assets/javascripts/application.js has the //= require_tree . directive
  • I deployed to heroku as described in Analytics for Rails
  • I did not include the rails_12factor gem as in https://github.com/heroku/rails_12factor says.

Google Analytics still don't get tracking data from my website. What am I missing?

I use slim templating, so make changes according to your templating engine. In application.html.slim in head initialize ga

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', 'UA-XXXXXXX-XX', 'auto');
  ga('send', 'pageview');

in ga.js.coffee

document.addEventListener 'turbolinks:load', (event) ->
  if typeof ga is 'function'
    ga('set', 'location', event.data.url)
    ga('send', 'pageview')

Bonus. I also use infinite scroll, so when I load data in index.js.erb I use this to send another page view to ga

ga('send', 'pageview');
... rest of the code

If you used this page http://reed.github.io/turbolinks-compatibility/google_analytics.html with the set up you posted above you need to change your application.js to application.js.coffee . All of that code is written in coffeescript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM