Jonas
Jonas

Reputation: 5149

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?

Upvotes: 9

Views: 7530

Answers (4)

evbruno
evbruno

Reputation: 196

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

Upvotes: 7

Rahul
Rahul

Reputation: 1876

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

Upvotes: 2

lunaclaire
lunaclaire

Reputation: 53

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

Upvotes: 3

Keith Gaddis
Keith Gaddis

Reputation: 4113

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.

Upvotes: 12

Related Questions