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

牧云@^-^@ 提交于 2020-01-01 10:02:44

问题


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'

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

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

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

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

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


回答1:


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.




回答2:


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 %>'


来源:https://stackoverflow.com/questions/15053678/rails-path-helpers-doesnt-work-in-js-coffee-erb

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!