Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
336 views
in Technique[技术] by (71.8m points)

javascript - Route helpers in asset pipeline

using Rails 3.1.0.rc4, I'm trying to access a route helper in a javascript file (event.js.erb in this case) and it seems like they are not loaded at that moment. When requesting the merged /assets/application.js file, I get:

throw Error("NameError: undefined local variable or method `events_path' for #<#<Class:0x00000001580010>:0x00000003191510>
  (in /<...>/app/assets/javascripts/event.js.erb)")

Any idea how to access the route helper in there?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

UPDATE: Now there is a gem that does this for you: js-routes


The problem is that Sprockets is evaluating the ERB outside of the context of your Rails app, and most of the stuff you're expecting isn't there.

You can add things to your Sprockets context like so:

Rails.application.assets.context_class.class_eval do
  include Rails.application.routes.url_helpers
end

That's all well and good, but getting the helpers that require an id to work is a little trickier. I'm going to use a technique called a URI Template:

var event_path = "<%= CGI.unescape event_path('{event_id}') %>";

which returns /events/{event_id} which you could render into a url using an object like { event_id: 1 }. See SugarJS's String#assign method as example implementation of this. You could also roll your own like I did.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...