Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Accessing a Model from js.erb file when precompiling

I have a Rails 3 app where I am trying to populate a javascript variable with every Nation in my database (less than 300 nations) as a JSON object. This is the relevant line in my nations.js.erb file:

_this.nations = <%= Nation.all.to_json :only => [:id], :methods => :text %>;

When I call my js file in a browser, /assets/users.js which does a require of the nations file, the _this.nations variable is populated perfectly. When I try to do a precompile I get the following:

$> rake assets:precompile
$> rake aborted!
uninitialized constant Nation (in nations.js.erb)

So my question is this: is it possible to reference the Nation model, or any model, from within the js.erb file for precompiling? I also tried using my NationsHelper but my error just changed to uninitialized constant NationsHelper.

I'm fairly new to RoR so if relevant information is needed that I haven't provided, please just ask.

like image 459
Eric Sanders Avatar asked Oct 15 '12 17:10

Eric Sanders


People also ask

Where do I put JavaScript ERB files?

Create the js. erb in the view folder itself with the same name as that of the action. In the view where some form is created which will be calling this action, make the request using :remote => true .

What is a js Erb file?

erb view file that generates the actual JavaScript code that will be sent and executed on the client side.

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

If you have config.assets.initialize_on_precompile set to false somewhere then try enabling it

config.assets.initialize_on_precompile = true
like image 197
Sully Avatar answered Sep 17 '22 13:09

Sully