1. Use a ruby simple object in Javascript. For example, convert a ruby object to a simple JavaScript variable:
<%= javascript_tag do %> url = '<%= j products_url %>';<% end %>
<% = %> Is enclosed by quotation marks. RailsJThe method is to correctly define the ruby object and embed it into JavaScript.
2. Using Ruby complex objects in Javascript is obviously JSON, but to correctly convert JSON, you needRawMethod:
<%= javascript_tag do %> products = <%= raw Product.limit(10).to_json %><% end %>
In this case, no quotation marks are enclosed. 3. If Gon gem has a large number of Ruby objects that need to be used in Javascript, this method is not good. GON is designed to solve this problem. First, add GON in gemfile:
gem 'gon'
Then GON is included in the/APP/views/layouts/application.html. ERB file:
Then, in controller, you can assign values to JavaScript objects in this form:
gon.variable_name = variable_value# or new syntaxgon.push({ :user_id => 1, :user_role => "admin"})gon.push(any_object) # any_object with respond_to? :each_pair
For example:
How to Get variables in JS:
gon.variable_name
That is:
go.products
References 1. gon2.passing data to Javascript