Passing array of objects to javascript

Hi

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.

Thanks
Jason

On Thu, Aug 16, 2012 at 6:23 AM, Jason W. [email protected]
wrote:

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


Dave A., Available Secret-Cleared Ruby/Rails Freelancer
(VA/DC/Remote);
see www.DaveAronson.com, www.Codosaur.us, and www.Dare2XL.com for more
info.

Dave A. wrote in post #1072670:

On Thu, Aug 16, 2012 at 6:23 AM, Jason W. [email protected]
wrote:

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


Dave A., Available Secret-Cleared Ruby/Rails Freelancer
(VA/DC/Remote);
see www.DaveAronson.com, www.Codosaur.us, and www.Dare2XL.com for more
info.

Hi Dave

Think i’ve find a solution using good old google - like you suggest
using object.to_json to create a data attribute on a div looks the way
to go.

cheers matey
Jase

On Fri, Aug 17, 2012 at 2:56 PM, Jason W. [email protected]
wrote:

Think i’ve find a solution using good old google - like you suggest
using object.to_json to create a data attribute on a div looks the way
to go.

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…

-Dave