3

I'm trying to make some charts on my app, and so I've started using http://www.jqplot.com/index.php

It uses arrays to input the data, so I'm trying to create some arrays of my data in ruby, that I can then print in the javascript.
i.e. @array_example = [1,2,3,4,5] wouldn't work when printed, but @array_example = "[1,2,3,4,5]" would work.

Anyway, The first my question would be, if I have:

<% @chart_posts = Post.where(:user_id => @profile.user.id) %>

Whats a good way to use this data to make an array (if I want the id of each post in the array, and a second array with the created_at)?

To be a little more clear, the final arrary needs to look like an array when printed.
i.e. it must have ['s around it, and ,'s in between each item.

1
  • 2
    Note: Since it looks like your Post model belongs_to :user and User model has_many :posts, you can instead write @profile.user.posts instead of that Post.where clause. Commented Feb 7, 2011 at 5:08

2 Answers 2

3

I'm not too clear on what your final array should look like, but I think map should get you what you need.

ids = @chart_posts.map(&:id) 
# => [1,2,3,4]

created_ats = @chart_posts.map(&:created_at) 
# => [timestamp,timestamp,timestamp,timestamp]

You could also combine that into a single 2D array with map as well:

array = @chart_posts.map {|post| [post.id, post.created_at]} 
# => [[1, timestamp],[2,timestamp]]
Sign up to request clarification or add additional context in comments.

2 Comments

To 'look like an array', if you are embedding it directly to javascript, you can use array.to_json to make sure all strings are escaped.
Alternatively, you could use array.inspect - it seems to aim for human-readable output.
1

Looks like grose php hackery...

but join what the guys above have said to return a couple of strings:

id_array_string = @chart_posts.map(&:id).inspect 
# => "[1,2,3,4]"

timestamp_array_string = @chart_posts.map(&:created_at).inspect

# => "[timestamp,timestamp,timestamp]"

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.