Sohail Aslam
Sohail Aslam

Reputation: 727

Adding google analytics in rails without turbolinks

I have removed turbolinks from my application for some reasons and now when I am trying to run google analytics, it is not working.

I used gem 'google-analytics-rails' and this customized solution. But none of them worked. Any idea how I can add google anayltics in my application without turbolinks?

Upvotes: 3

Views: 503

Answers (1)

Dan
Dan

Reputation: 1246

I typically just place this in the ApplicationHelper like so

module ApplicationHelper

  def ga_script
    tracking_id = ""
    if Rails.env.production?
      javascript_tag("(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', '#{tracking_id}', 'auto');")
    end
  end

  def ga_track
    javascript_tag("if(window.ga != undefined){ga('send', 'pageview');}")
  end

end

Then in a layout file:

<head>
   <%= ga_script %>
</head>
<body>
...
   <%= ga_track %>
</body>

Its simple and it works with/without Turbolinks.

Alternatively, stop trying to complicate it and simply paste the GA script at the bottom of the body section of your layout.

Upvotes: 2

Related Questions