Using a Rails helper method within a javascript asset

前端 未结 5 2201
长发绾君心
长发绾君心 2020-11-28 03:13

Is there any way to use a Rails helper method, more specifically, a path helper method within a javascript asset file. This file foo.js.coffee.erb



        
5条回答
  •  佛祖请我去吃肉
    2020-11-28 03:29

    This will also do the trick in an initializer:

    Sprockets::Context.send :include, MyHelper
    

    In development mode the helper will not be reloaded on every request.

    Your approach with UrlHelpers will work until you need to find post_path(...um...we don't know what post id we'll need at compile time...). There is a ruby gem which reimplements all of your Rails UrlHelpers in JavaScript: https://github.com/railsware/js-routes

提交回复
热议问题