randombits
randombits

Reputation: 48490

Properly embed JavaScript variables in Ruby on Rails 4.x

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?

Upvotes: 0

Views: 87

Answers (1)

benjaminjosephw
benjaminjosephw

Reputation: 4417

One problem here is simply that your file should be called foo.js.erb to compile ruby.

Also, I think you want to do this:

var class_a = <%= @students.select { |s| s.class_id == 'a' }.to_json %>

(Notice the double equal sign)

You might even be better to find the specific student in your controller and pass each through individually - this would be a better separation of concerns and would keep this logic out of your views.

Upvotes: 2

Related Questions