Passing array of objects to javascript


I am looking for the best way to get an array of objects from the
database, pass them to the view in an instance variable, then make the
array available to a javascript attached to the view.


What part are you having trouble with? What have you tried? Why
didn't it work? (What happened instead?)

The first two parts are very basic to any Rails app, so I'll assume
it's the third. Depending on your exact situation, you probably need
to look at Object#to_json and use that in some ERb (or HAML or
whatever you use) in your view. (The code that actually does
something with it can and should be elsewhere, but I think the call
will need to be directly in the view.)


Dave Aronson wrote in post #1072670:

Using a data attribute on a div could work. Or you could make it the
contents of a hidden div. Or you could assign the value to an object
and use the object in a call to a JS function defined separately. Or
you could do similarly with a literal. Or you could make your JS
obtrusive instead of defining it elsewhere. There are a gazillion
ways you could go with it, but yeah, it mostly boils to to_json....