我正在尝试在我的 Rails 应用程序的 erb 文件中运行以下行:
<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>
我在包含 <%=current_user.id%>
的行中收到错误,即使不满足条件,也似乎可以分析:
Called id for nil, which would mistakenly be 8 -- if you really wanted the id of nil, use object_id
我如何处理带有 ruby 变量的 javascript 条件?
最佳答案
在 erb 文件中,我们可以使用脚本嵌入 ruby 代码:<% %>
.
这应该有效:
<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>
关于javascript - ERB Javascript 条件错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34095511/