在我的 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 助手吗?
最佳答案
这是因为您不在 Assets 内的 View 上下文中。向文件添加 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 帮助程序的成员路由,因为这绝对不适用于 coffeescript。请记住,在生产中 Assets 是预编译的,因此您不能使用任何动态的东西。为此,您只能真正依靠在 Controller 中设置操作来响应 JS 调用。
关于ruby-on-rails - Rails 路径助手在 js.coffee.erb 中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15053678/