Ruby inside CoffeeScript
posts.js.coffee.erb
$('.list').infinitescroll {url: '<%= list_posts_path %>', triggerAt: 700, container: $('.container'), appendTo: $开发者_StackOverflow中文版('.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?
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.
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} !!!"
another alternative is to set a data attribute holding your path on some relevant element... then grab it with the js/coffee code
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
精彩评论