0

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?

1
  • Try to use the gon gem Commented Feb 24, 2014 at 21:05

1 Answer 1

2

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.

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

2 Comments

Do I then have to add foo.js to my HTML?
You should checkout the docs on the Asset Pipeline to understand how it all works together: guides.rubyonrails.org/asset_pipeline.html

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.