1

I am trying to run the following lines in my Rails app in an erb file:

<script>
  if("<%=current_user%>".length>0){
    console.log('set mixpanel current user');
    mixpanel.identity("<%=current_user.id%>");
  }else{
    console.log('set mixpanel identity to 0');
    mixpanel.identify('0');
  }
</script>

I am getting errors with the line containing <%=current_user.id%>, which seems to be analyzed even if the conditional is not satisfied:

Called id for nil, which would mistakenly be 8 -- if you really wanted the id of nil, use object_id

How do I handle a javascript conditional with a ruby variable?

2 Answers 2

4

In erb file, we can embed ruby code using scriptlets: <% %>.

This should work:

<script>
  <% if current_user %>
    console.log('set mixpanel current user');
    mixpanel.identity("<%=current_user.id%>");
  <% else %>
    console.log('set mixpanel identity to 0');
    mixpanel.identify('0');
  <% end %>
</script>
Sign up to request clarification or add additional context in comments.

Comments

0

current_user instead of "<%=current_user%>".length>0 would work I guess.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.