I am using Ruby on Rails 4 and am trying to write a JavaScript that requires server-side data to populate. For instance, I might have a control called StudentsController and I want to return all particular students from a particular class. So in my controller I might do:
def index
@students = Student.all
end
I then have a script in /app/assets/javascripts/ called foo.js and in there I'm trying to split the students up by their class_id.
in foo.js
$(function() {
var class_a = <%= @students.select { |s| s.class_id = 'a' }.to_json %>
var class_b = <%= @students.select { |s| s.class_id = 'b' }.to_json %>
})
Problem is class_a is null when I'm checking on the browser side of things. I'm assuming foo.js isn't linked up to StudentsController and doesn't see @students. What's the right way to wire JavaScript this way so I can have access to javascript variables with my server-side objects?