Francois
Francois

Reputation: 10631

How do I pass an Array of ids from Rails 3 controller to a Javascript Array?

Im trying to grab the ids of the images using rails, pass those ids to javascript and then flip through them using a javascript Image Viewer.

This is what I have in my rails controller

@rails_array = Images.all


this is in my view file

<script type="text/javascript" >
 var myIds=new Array(<% @rails_array %>);
</script>

Upvotes: 1

Views: 1947

Answers (3)

Srikanth Jeeva
Srikanth Jeeva

Reputation: 3011

You can collect Ids from controller like this:

@rails_array = Images.all.map &:id

In the View:

<script type="text/javascript" >
   var myIds= <%= @rails_array %>
</script>

Upvotes: 3

Marc-Andr&#233; Lafortune
Marc-Andr&#233; Lafortune

Reputation: 79562

A good way to pass any object to javascript is through JSON:

var myId= <%= @rails_array.to_json %> ;

Note: You'll need to append .html_safe for strings & hashes (or arrays containing them), but it isn't needed for arrays of integers.

Upvotes: 2

Awais Qarni
Awais Qarni

Reputation: 18006

Hi have you tried split() method of javascript

 <script type="text/javascript">
  var myId=<% @rails_array %>.split(/,/);
 </script>

Upvotes: 1

Related Questions