Ruby inside CoffeeScript

posts.js.coffee.erb

$('.list').infinitescroll {url: '<%= list_posts_path %>', triggerAt: 700, container: $('.container'), appendTo: $('.container'), page: 1} 

This makes an exception:

throw Error ("NameError: undefined local variable or` list_posts_path 'method for # <#: 0x00000003557438> \ n ...

list_posts_path returns the correct path if I use it in the controller. What am I doing wrong?

+8
ruby-on-rails coffeescript
source share
4 answers

Yes, do not do this. :)

You do not have a controller, although you use ERB. The coffeescript compiler knows nothing about your routes or routing assistants, which your views usually access through the controller.

+12
source share

I had the same problem, and as mentioned earlier, you could do something like:

your_layout.html.erb

<%= render partial: 'your_partial.html.erb', locals: { action_url: list_posts_path } %>

_your_partial.html.erb

<div id='container' data-action-url="<%= action_url %>" .... >

posts.js.coffee.erb

jQuery -> url = $('#container').data('action-url') console.log "loading url: #{url} !!!"

+7
source share

Another alternative is to set a data attribute holding your path to some appropriate element ... then capture it with js / coffee code

+3
source share

turn on

 <% environment.context_class.instance_eval { include Rails.application.routes.url_helpers } %> 

at the beginning of the coffeescript file, and then you can access the routes

+2
source share

All Articles