Rails path-helpers doesn't work in js.coffee.erb

我的未来我决定 提交于 2019-11-29 07:15:42

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")

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)

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.

Old post, but still accessible from Google.

In rails 4 (and certainly at least 3 too) you can use the route helpers to insert your js files easily:

assets/javascript/my_file.js.coffee.erb

<% self.class.include Rails.application.routes.url_helpers %>
window.index_route = '<%= index_path %>'
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!