Rails: access controller instance variable in CoffeeScript or JavaScript asset file

前端 未结 6 1138
我寻月下人不归
我寻月下人不归 2020-12-01 01:19

In Rails 3.1 it is not possible to access controller instance variables in an asset js.erb or coffee.erb file using syntax such as <%= @foo %>, where @foo is set in the c

6条回答
  •  Happy的楠姐
    2020-12-01 02:14

    In situations where your javascript data gets out of hand, using the gon gem is still the preferred way to go in rails, even in 2015. After setting up gon, you are able to pass data to your javascript files by simply assigning the data to the gon object in rails.

    (Gemfile)
    gem 'gon'
    
    (controller) 
    def index 
      gon.products = Product.all 
    
    (layouts) 
    <%= include_gon %> 
    
    (public/javascripts/your_js_can_be_here.js) 
    alert(gon.products[0]['id'); 
    
    (html source automatically produced) 
    
    
                                     
                  
提交回复
热议问题