简体   繁体   中英

session variable is not recognized anymore after migrating js code to assets/javascripts in rails app

I moved some javascript that was in a content_for(:after_js) at the end of an html page to a proper js file inside my assets/javascripts folder in my rails app. I created a js.erb file that looks like this :

 <% if session[:user_role] == "asso" %>
    <%= render "javascripts/select_bar/_select_bar_asso.js"%>
 <% else %>
    <%= render "javascripts/select_bar/_select_bar_host.js"%>
  <% end %>

but now I always get the error :

undefined local variable or method `session' for #<#:0x007feb90e24400>.

It was working fine when the js was in the content_for(:after_js) at the end of my html.erb file and it was ok with the session variable.

What did I do wrong with my javascript migration ?

You should pass the session variable as local variable to the partial, take a look here and search for section 3.4.4 Passing Local Variables .

To simplify, this is how you should render your js partial:

<%= render partial: "my_js", locals: {session: session} %>

Your partial should remain the same.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM