Reputation: 4728
I am using the following google analytics code to track users in my Ruby on Rails 4 app
// ga('create', 'UA-1234567-1', 'auto');
ga('create', 'UA-1234567-1', 'auto', { 'userId': <%= current_user.id %> });
// ga('set', '&uid', <%= current_user.id %>); // Set the user ID using signed-in user_id.
ga('send', 'pageview');
but I am getting the error
undefined method `id' for nil:NilClass
for the line
ga('create', 'UA-1234567-1', 'auto', { 'userId': <%= current_user.id %> });
I am following this thread How do I set USER_ID in Google Universal Analytics tracking code in Rails? and official doc https://developers.google.com/analytics/devguides/collection/analyticsjs/cookies-user-id but not sure what is going wrong as it is almost same code.
Upvotes: 0
Views: 916
Reputation: 6942
I'd recommend sending a zero in the case of an anonymous user since this condition will never exist in your production database. That way you can still track those users if you ever decide you need to.
If you're fine doing that then this should do the trick:
ga('create', 'UA-1234567-1', 'auto', {'userId': <%= user_signed_in? ? current_user.id : 0 %>})
Here's a link to the documentation for user_signed_in?
https://github.com/plataformatec/devise#controller-filters-and-helpers
Upvotes: 0
Reputation: 6531
Add a check condition for logged_in user only -
<% if current_user.present? %>
<script>
//analytics stuffs
ga('create', 'UA-1234567-1', 'auto', { 'userId': <%= current_user.id %> }); // Set the user ID using signed-in user_id.
ga('send', 'pageview');
</script>
<% end %>
Or
<script>
//analytics stuffs
ga('create', 'UA-1234567-1', 'auto', { 'userId': <%= current_user.present? ? current_user.id : nil %> }); // Set the user ID using signed-in user_id.
ga('send', 'pageview');
</script>
Upvotes: 1