在没有 turbolinks 的情况下在 rails 中添加 google 分析

Adding google analytics in rails without turbolinks

由于某些原因,我已经从我的应用程序中删除了 turbolinks,现在当我尝试 运行 google 分析时,它不起作用。

我用了 gem 'google-analytics-rails' 和 但是 none 有效。知道如何在没有 turbolink 的情况下在我的应用程序中添加 google 分析吗?

我通常只是像这样将它放在 ApplicationHelper 中

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

然后在布局文件中:

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

它简单而且有效 with/without Turbolinks。

或者,停止尝试使其复杂化,只需将 GA 脚本粘贴到布局正文部分的底部即可。