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

前端 未结 2 1546
清酒与你
清酒与你 2020-12-18 05:36

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


        
相关标签:
2条回答
  • 2020-12-18 05:54

    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.

    0 讨论(0)
  • 2020-12-18 06:16

    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 %>'
    
    0 讨论(0)
提交回复
热议问题