Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 method `list_posts_path' for #<#:0x00000003557438>\n ...

list_posts_path returns correct path if I use it in controller. What I do wrong?

like image 255
Jonas Avatar asked Sep 12 '11 17:09

Jonas


4 Answers

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.

like image 154
Keith Gaddis Avatar answered Sep 28 '22 08:09

Keith Gaddis


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

like image 35
evbruno Avatar answered Sep 28 '22 07:09

evbruno


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

like image 43
lunaclaire Avatar answered Sep 28 '22 06:09

lunaclaire


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

like image 39
Rahul Avatar answered Sep 28 '22 06:09

Rahul