Reputation: 665
I have this code-snippet:
in my app/assets/javascripts/application.js
//= require jquery
//= require harddisk
//= require rails-ujs
//= require_tree .
in my app/assets/javascripts/harddisk.js.erb
var harddisk_locations = [<%= raw @harddisk_locations.to_json %>];
console.log(harddisk_locations);
in my app/models/harddisk.rb
@harddisk_locations = ["foo", "bar", "baz"];
But for some reason on the harddisk page in browser console
@harddisk_locations is null instead of an array with 3 elements.
Why is it so and how to fix?
It doesn't help if I move the
@harddisk_locations = ["foo", "bar", "baz"];
from harddisk-model into harddisks_controller.rb
Upvotes: 0
Views: 55
Reputation: 476
You should be defining them to a global variable instead of an instance variable. You can change your model code to:
HD_LOCATIONS = ['foo', 'bar', 'baz']
and in you JS file:
var harddisk_locations = [<%= raw Harddisk::HD_LOCATIONS.to_json %>];
You can read more about variable types here: https://www.tutorialspoint.com/ruby/ruby_variables.htm
Upvotes: 1