GON - not getting value in js.erb + Rails 5

1.2k Views Asked by At

Gem File

gem 'gon'

This is my application.html.erb File.

<html>
  <head>
    <title>Test Title</title>
    <%= Gon::Base.render_data %>
    <%= include_gon(:init => true) %>
    <%= csrf_meta_tags %>
    <%= stylesheet_link_tag    'application', media: 'all', 'data-turbolinks-track': 'reload' %>
    <%= javascript_include_tag 'application', 'data-turbolinks-track': 'reload' %>           
  </head>
  <body>
    ....
  </body>
</html>

Now, On many pages(Index) I delete my records with ajax. like

<%= link_to "<i class='fa fa-times-circle-o'></i>".html_safe, section_path(sec_content, type: params[:type]), class: 'pull-right', title: 'Delete Section', data: {disable_with: "<i class='fa fa-spinner'></i>".html_safe, confirm: 'Are you sure want to delete ?'}, method: :delete, remote: true %>

In Controller, Destroy action code.

def destroy
  gon.test_id = 1
  section.destroy if section.present?      
end

Now, It's goes to destroy.js.erb file

console.log(gon)
alert(gon.test_id)
$("#section_<%= params[:id] %>").remove();

Now, the console.log nothing to display and alert will comes but it display me 'undefine'

Can anyone help me what's wrong in above code so I can use gon in js.erb files ?

Thanks in advance

2

There are 2 best solutions below

1
On

mark require 'gon' in controller & try.

1
On

Afaik you have to use gon watch to use Gon with Ajax.


You also should do

<%= Gon::Base.render_data(init: true) %>

# instead of 
# <%= Gon::Base.render_data %>
# <%= include_gon(:init => true) %>