Search code examples
javascriptrubyruby-on-rails-4gon

undefined local variable or method `gon' for ApplicationController:Class in rails 4.2


I can't seem to get the gon gem working with rails 4.2.0. I am getting "undefined local variable or method `gon' for #" Am I using it correctly? Also I do have the <%= include_gon(:init => true) %> in the header of my layout 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>


Solution

  • Place this code in a method For ex:

    def methodname
    gon.current_user_rolename = current_user.role.name
    end
    

    It wont work if you define outside a method

    Also place this lines as follows in application.html.erb below csrf_metags line:

     <%= csrf_meta_tags %>
    <%= include_gon(:init => true) %>
        <%= Gon::Base.render_data({}) %>