我似乎无法让gon gem使用rails 4.2.0。我正在为#“获取未定义的局部变量或方法`gon'”我是否正确使用它?我也有<%= include_gon(:init => true)%>在我的布局application.html.erb的标题中。
的ApplicationController
class ApplicationController < ActionController::Base
gon.current_user_rolename = current_user.role.name
end
的application.js
if(gon.current_user_rolename == 'Admin'){
alert('success');
}
Application.html.erb
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<%= include_gon(:init => true) %>
<%= Gon::Base.render_data({}) %>
<!-- Main css styles -->
<%= stylesheet_link_tag 'application', media: 'all', 'data-turbolinks-track' => true %>
<!-- Main javascript files -->
<%= javascript_include_tag 'application', "http://localhost:9292/faye.js", 'data-turbolinks-track' => true %>
<%= csrf_meta_tags %>
</head>
<body >
<%=yield%>
</body>
答案 0 :(得分:3)
将此代码放在方法中,例如:
def methodname
gon.current_user_rolename = current_user.role.name
end
如果您在方法外定义
,它将无法工作同样在csrf_metags行下面的application.html.erb中放置以下行:
<%= csrf_meta_tags %>
<%= include_gon(:init => true) %>
<%= Gon::Base.render_data({}) %>