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 method `list_posts_path' for #<#:0x00000003557438>\n ...
list_posts_path returns correct path if I use it in controller. What I do wrong?
4 Answers 4
Yeah, don't do that. :)
You're not inside a controller, even though you're using ERB. The coffeescript compiler doesn't know anything about your routes or routing helpers, which your views typically get access to through the controller.
2 Comments
<script> tag into your page (via the view or a layout) that provides just that data. (Or, if the data doesn't need to be available on page load, use Ajax.) That way, all your other JS can be concatenated, minified, and cached.I had the same issue, and as mentioned early, 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} !!!"
Comments
another alternative is to set a data attribute holding your path on some relevant element... then grab it with the js/coffee code
Comments
include
<% environment.context_class.instance_eval { include Rails.application.routes.url_helpers } %>
at the beginning of the coffeescript file and then you will be able to access routes