问题
Here's the Universal Analytics tracking code for my Rails-based app. (It can be found in _analytics.html.erb, which is loaded as a partial in application.html.erb)
<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-44709438-1', 'auto');
ga('set', '&uid', {{USER_ID}}); // Set the user ID using signed-in user_id.
ga('send', 'pageview');
</script>
Question: how do I set USER_ID using Ruby? Is the following right?
ga('set', '&uid', <% current_user.id %>); // Set the user ID using signed-in user_id.
If not, how can I do this?
回答1:
As per directive given in google analytics
You should do like this
ga('create', 'UA-XXXX-Y', { 'userId': <%= current_user.id %> })
and link it in application.html.erb exactly before closing of head tag
use this link for reference https://developers.google.com/analytics/devguides/collection/analyticsjs/user-id
Also you may need to add condition to decide whether the user is logged in or not
来源:https://stackoverflow.com/questions/25041519/how-do-i-set-user-id-in-google-universal-analytics-tracking-code-in-rails