Rails路径助手在js.coffee.erb中不起作用

BBQ*_*hef 6 ruby-on-rails coffeescript ruby-on-rails-3 asset-pipeline ruby-on-rails-3.2

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

undefined local variable or method `new_user_session_path'
Run Code Online (Sandbox Code Playgroud)

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

= link_to t('user.login'), new_user_session_path
Run Code Online (Sandbox Code Playgroud)

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

$.get("<%= new_user_session_path %>")
Run Code Online (Sandbox Code Playgroud)

是不是可以在coffeescript erb中使用x_path和x_url助手?

Clu*_*ter 12

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

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

$.get("/sign_in")
Run Code Online (Sandbox Code Playgroud)

如果你真的想要,你可以创建一个部分输出一个脚本标签,将你的助手方法输出到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)
Run Code Online (Sandbox Code Playgroud)

另外值得记住的是,对于将模型实例传递给url帮助器的成员路由,这显然不适用于coffeescript.请记住,在生产资产中进行了预编译,因此您无法使用任何动态资源.为此,您只能依靠在控制器中设置操作来响应JS调用.


Ben*_*enj 8

旧帖子,但仍可从谷歌访问.

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

资产/ JavaScript的/ my_file.js.coffee.erb

<% self.class.include Rails.application.routes.url_helpers %>
window.index_route = '<%= index_path %>'
Run Code Online (Sandbox Code Playgroud)