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.
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 .
erb view file that generates the actual JavaScript code that will be sent and executed on the client side.
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.
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 .
If you have config.assets.initialize_on_precompile
set to false
somewhere then try enabling it
config.assets.initialize_on_precompile = true
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With