简体   繁体   English

将JS代码迁移到Rails应用程序中的资产/ JavaScript之后,会话变量不再被识别

[英]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. 我将html页面末尾的content_for(:after_js)中的一些javascript移到了我的rails应用程序中asset / javascripts文件夹内的适当js文件中。 I created a js.erb file that looks like this : 我创建了一个js.erb文件,看起来像这样:

 <% 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>. #<#:0x007feb90e24400>的未定义局部变量或方法'session'。

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. 当js位于html.erb文件末尾的content_for(:after_js)中时,它工作正常,并且可以使用会话变量。

What did I do wrong with my javascript migration ? 我的JavaScript迁移有什么错?

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 . 你应该在会话变量作为局部变量传递到局部,看看这里 ,搜索第3.4.4传递局部变量

To simplify, this is how you should render your js partial: 为简化起见,这是您应如何部分渲染js的方法:

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

Your partial should remain the same. 您的局部应该保持不变。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 Rails 4:application.js中的“ // = require_tree”在/ app / assets / javascripts中不包含我的js文件 - Rails 4: “//= require_tree .” in application.js doesn't include my js file in /app/assets/javascripts `application.js`不再包括Rails 3.1应用程序的app / assets / javascripts中的所有脚本 - `application.js` no longer including all scripts in app/assets/javascripts for Rails 3.1 app 如何从Rails的“查看”页面中的/ app / assets / javascripts文件夹中调用JS脚本? - How can I call upon a JS script in my /app/assets/javascripts folder from a View page in Rails? 'createConsumer' 不是由 node_modules/@rails/actioncable/app/assets/javascripts/action_cable.js 导出的 - 'createConsumer' is not exported by node_modules/@rails/actioncable/app/assets/javascripts/action_cable.js Rails 4.1.1:lib / assets / javascripts中的JS文件未加载 - Rails 4.1.1: JS file in lib/assets/javascripts doesn't load Rails没有在app / assets / javascripts下注册javascript文件 - rails not registering javascript files under app/assets/javascripts Rails递归地包含javascripts资源文件夹 - Rails include javascripts assets folder recursively Rails应用程序未使用资产加载javascripts文件 - Rails application not loading javascripts files using assets Ruby on Rails:我的部分资产(javascripts)的资产管道失败 - Ruby on Rails: Asset pipeline failing for only some of my assets (javascripts) 如何将JavaScript值检入Rails变量 - How to check JavaScripts values into a rails variable
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM