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开发者_Go百科
)?
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.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]]
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]"
精彩评论