Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails 3.1: Asset pipeline with named routes

Rails 3.1.0.rc5

I am having trouble getting named routes to work within an ERB-enabled Javascript file:

# app/assets/javascripts/items.js.erb
$('#start').click(function() {
  $.ajax({
    url : '<%= ajax_items_path %>',
    success : function(result) {
      $('#result').html(result);
    }
  });
});

The error message is as follows:

Error compiling asset items.js:
NameError: undefined local variable or method `ajax_items_path' for #<#<Class:0x007fbcb49a7630>:0x007fbcb4ee30b8>
  (in myproject/app/assets/javascripts/items.js.erb)

The ajax_items_path route works fine if I use it directly in a view.

It looks like named routes aren't available within the Asset Pipeline. If this is the case, what is the workaround? I really want to avoid hard-coding URLs in my Javascript.

like image 242
gjb Avatar asked Aug 11 '11 10:08

gjb


People also ask

How do you Precompile rails assets?

To compile your assets locally, run the assets:precompile task locally on your app. Make sure to use the production environment so that the production version of your assets are generated. A public/assets directory will be created. Inside this directory you'll find a manifest.

How does Rails asset pipeline work?

The asset pipeline provides a framework to concatenate and minify or compress JavaScript and CSS assets. It also adds the ability to write these assets in other languages such as CoffeeScript, Sass and ERB. Prior to Rails 3.1 these features were added through third-party Ruby libraries such as Jammit and Sprockets.

What is assets Precompile?

rails assets:precompile is the task that does the compilation (concatenation, minification, and preprocessing). When the task is run, Rails first looks at the files in the config.assets.precompile array. By default, this array includes application.js and application.css .


1 Answers

A workaround is to use your route helpers from Rails.application.routes.url_helpers, e.g.

<%= Rails.application.routes.url_helpers.ajax_items_path %>
like image 120
tristanm Avatar answered Oct 10 '22 04:10

tristanm