7

在我的 Rails 3.2 应用程序(Ruby 1.9)中,在 Coffeescript 中使用路径助手时出现以下错误。

undefined local variable or method `new_user_session_path'

在我的部分 _usermenu.html.haml 工作正常:

= link_to t('user.login'), new_user_session_path

在我的 app/assets/javascripts/metamenu.js.coffee.erb 中抛出上述错误:

$.get("<%= new_user_session_path %>")

不能在coffeescript erb 中使用x_path 和x_url 助手吗?

4

2 回答 2

13

这是因为您不在资产内的视图上下文中。向文件添加 erb 扩展名不会改变这一点,它只是允许您评估嵌入式 ruby​​。

如果这是一次性场景,最好的办法是简单地使用字符串本身。

$.get("/sign_in")

如果你真的想要,你可以创建一个输出脚本标签的部分,将你的帮助方法输出到 js 变量中并以这种方式访问​​它们。

# in your layout

<%= render 'url_helpers' %>

# in app/views/layouts/_url_helpers.html.erb

<script>
  window.new_user_session_path = "<%= new_user_session_path %>";
  # add more if necessary
</script>

# in your coffeescript

$.get(@new_user_session_path)

还值得记住的是,这显然不会适用于您将模型实例传递给 url 助手的成员路由,因为这绝对不适用于咖啡脚本。请记住,在生产中资产是预编译的,因此您不能使用任何动态的东西。为此,您只能真正依靠在控制器中设置操作来响应 JS 调用。

于 2013-02-24T19:52:03.250 回答
8

旧帖子,但仍可从 Google 访问。

在 rails 4(当然至少也有 3 个)中,您可以使用路由助手轻松插入您的 js 文件:

资产/javascript/my_file.js.coffee.erb

<% self.class.include Rails.application.routes.url_helpers %>
window.index_route = '<%= index_path %>'
于 2015-09-02T16:42:07.167 回答