Trinity76
Trinity76

Reputation: 665

Rails: "null" instead of an array with 3 elements when trying to use ruby array in javascript

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

Answers (1)

Ravi Teja Dandu
Ravi Teja Dandu

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

Related Questions