0

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

1

1 Answer 1

1

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

Sign up to request clarification or add additional context in comments.

2 Comments

then I get an error: "uninitialized constant ERB::HD_LOCATIONS"
I have updated my code. Could you please try it once and in case it throws an error, paste the exception stack?

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.