Rails路径帮助器在js.coffee.erb中不起作用 [英] Rails path-helpers doesn't work in js.coffee.erb

查看:102
本文介绍了Rails路径帮助器在js.coffee.erb中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

In my Rails 3.2 app (Ruby 1.9) I get following error when using path helpers in Coffeescript.

undefined local variable or method `new_user_session_path'

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

In my partial _usermenu.html.haml that works fine:

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

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

In my app/assets/javascripts/metamenu.js.coffee.erb that throws above error:

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

在erb脚本中不能使用x_path和x_url帮助器吗?

Isn't it possible to use x_path and x_url helpers in coffeescript erb's?

推荐答案

这是因为您不在资产内部的视图上下文中.在文件中添加erb扩展名并不会改变它,它只允许您评估嵌入的红宝石.

This is because you are not within the view context inside of your assets. Adding an erb extension to the file doesn't change this, it simply allows you to evaluate embedded ruby.

如果这是一次性情况,最好的选择是仅使用字符串本身.

If this is a one-off scenario, your best bet is to simply use the string itself.

$.get("/sign_in")

如果确实需要,可以创建一个输出脚本标签的局部文件,该脚本标签将您的辅助方法输出到js变量中并以这种方式访问​​它们.

If you really wanted to you could create a partial that output a script tag that output your helper methods into js variables and access them that way.

# 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.请记住,在生产中资产是预编译的,因此您不能使用任何动态的东西.为此,您只能真正依靠在控制器中设置操作来响应JS调用.

Also worth keeping in mind that this will obviously never work for member routes where your passing an instance of a model to the url helper as that is definitely not available to coffeescript. Remember, in production assets are precompiled so you can't use anything dynamic. For that you can only really rely on setting up actions in your controller to respond to JS calls.

这篇关于Rails路径帮助器在js.coffee.erb中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆