[Java] [Rails 5] How to use gem gon ~ How to pass variables from Rails to JS ~

1 minute read

Implemented functions

Development environment

ruby> 2.6.5
rails >
gon> 6.3.2

This time, simply pass the variable defined in Rails Controller to JS and display it in html. It may be smoother to write in the hoge.js.erb format that is standardly installed in Rails or coffeescript, but I thought that it is a Gem that can be used as a workaround when it can not be displayed well, so I will introduce it. ..

※Note Since the variable itself is displayed in the html source according to the Gem specifications, it is better not to use it for something that needs to be hidden for security.

Introduction method

First, add to Gemfile



And install


$ bundle install

Write code in View of Rails This time it is supposed to be used on all pages, but it is OK if it is described in the required view. As with loading JS, the behavior differs depending on the loading timing, so be careful about the loading order.


<%= include_gon %>
<%= javascript_include_tag "application" %>

Now you are ready.

Pass variables

Define Gon variable in Rails Controller. However, just add gon. to the head of the variable.


def show
  @user = User.find(1)
  gon.username = @user.name # pass this to JS

Pass the variable to JS and display it in html.


<p id="name"></p>


let name = gon.username

It is OK if it is displayed like this.


<p id="name">Go here</p>

About the display in ####html

At the beginning I talked about “I see variables in html” It is actually read like this. It has a structure that is easy to understand whether it is good or bad.


      window.gon={};gon.username="This is it";

Other functions

Besides simply passing variables

  • Pass array, hash
  • Read all variables

It seems that you can also use such as. Rather, this may be the bigger role of Gem. For details, please check the official page.

Gon Official https://github.com/gazay/gon