javascript - js : undefined local variable or method `current_user'

标签 javascript ruby-on-rails angularjs ruby-on-rails-4

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

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

但是我发现了一个错误未定义的局部变量或方法current_user,它指向

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

我该如何解决这个问题?谢谢!

最佳答案

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

在你的 Controller 中

# 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 %>
  ...

在你的 JavaScript 中

var hello = gon.current_user_name;

关于javascript - js : undefined local variable or method `current_user' ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24500077/

相关文章:

javascript - 如何动态添加格式化的刻度?

ruby-on-rails - 如何嵌入Haml的错误::Engine in a web page in production on Heroku

ruby-on-rails - rails : How do self-referential has_many models work?

javascript - Angularjs ng-click 在 Kendo Grid 中不起作用

javascript - 在 Java 中访问 JavaScript 对象的字段

javascript - 将产品 ID 传递给 PayPal 按钮

javascript - 在SVG中,有一种方法可以在填充= "none"时在任何地方抓取形状

ruby-on-rails - Rails 4 : how to allow user to submit form with enter key, 没有提交按钮

angularjs - 在 API 网关中启用 CORS

angularjs - 如何更改 Angular Material 中 md 图标的颜色?