9

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?

asked Sep 12, 2011 at 17:23

4 Answers 4

12

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.

answered Sep 12, 2011 at 17:39
Sign up to request clarification or add additional context in comments.

2 Comments

Is there a way how to get that path in to js?
@Jonas The best way to make server-side data available to the JS is to put a <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.
7

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} !!!"

answered Mar 13, 2014 at 4:16

Comments

3

another alternative is to set a data attribute holding your path on some relevant element... then grab it with the js/coffee code

answered Aug 6, 2012 at 22:47

Comments

2

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

answered Jul 31, 2013 at 7:48

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.