Js:未定义的局部变量或方法current_user'

js: undefined local variable or method `current_user'

本文关键字:user current 方法 未定义 局部变量 Js      更新时间:2023-09-26

我有嵌入ruby代码的js文件:

function MyController($scope) {
  $scope.sayHello = function() {
    var hello = <%= current_user.name %>;
    $scope.greeting = hello;
  };
}

但是我发现了一个指向

的错误undefined local variable or method current_user

= javascript_include_tag "application", "data-turbolinks-track" => true

我该如何修复它?谢谢!

使用gon gem https://github.com/gazay/gon最简单的方式将数据从rails环境传递到javascript环境(换句话说:从服务器到客户端)。

在你的控制器

# Make sure first that current_user is not nil
gon.current_user_name = current_user.name
# As you can see we don't pass the whole `current_user` but only the data we need
#   gon and javascript won't know how to use your Rails objects
#   so pass only strings, integers, arrays and hashs
#   (but you'll figure out all of this by your self, it's pretty natural)

布局(更多关于gon安装的信息可以在gon github页面中找到)

<head>
  <%= include_gon %>
  ...

var hello = gon.current_user_name;

JS

扩展Benjamin Sinclaire的答案,你必须记住Rails是一个back-end系统;JS是front-end .

这意味着所有的Rails变量只在后端Rails文件中可用——浏览器接收到的是一组预渲染的HTML文件,其中填充了您的数据

你的问题是,JS不能读取Rails数据没有数据翻译从Rails到"JS"。所有JS看到的是DOM——页面上的HTML元素

,

为了在JS/front-end中共享current_user等变量,您基本上需要将其传递到HTML层

您可以通过设置隐藏元素(并设置其数据属性)或在layout

中设置变量来实现此目的。如前所述,最有效的方法是使用gon gem, Benjamin Sinclaire已经讨论过了