0

In my rails app, I have a loop in my controller that does this:

event_prices = []
event_dates = []
for event in @customer.events
  event_prices.push(event.total_prices)
  event_dates.push(event.event_time.strftime("%b %d, %Y at %I%p"))
end

I then use the arrays to push data into a highcharts graph. What I want to do is sort the event_dates array in order, but if I do that, I'll lose the order of the event_prices. Right now, the event_price[1] corresponds to event_dates[1] and so on, but if I call a sort! on event_dates, it won't sort event_prices along with it.

So how can I get it so that I sort both arrays the same way?

2 Answers 2

4

It's better to use DB for sorting. I would do the following:

event_prices, event_dates = 
  @customer.events(:order => "event_time ASC").map do |e|
    [e.total_prices, e.event_time.strftime("%b %d, %Y at %I%p")]
  end.transpose
Sign up to request clarification or add additional context in comments.

Comments

2

How about something like:

event_prices = []
event_dates = []
@customer.events.sort_by { |e| e.event_time }.each do |event|
  event_prices << event.total_prices
  event_dates << event.event_time.strftime("%b %d, %Y at %I%p")
end

5 Comments

Wow, you are a ruby wizard :) Thanks
Btw this will by default sort them oldest to newest. To get the reverse you could just reverse the list, or alternatively save off the current date now = Time.now and then make the block to sort_by like so: now - e.event_time.
Thanks again. I actually want oldest to newest, so this is great :)
No problem. Let me know if you have a problem... just in case I fat-fingered it. Also keep in mind that you can do this through your association (as in @customer.events(...) or using named scopes like defining @customer.ordered_events) but this might not be a big deal for your use-case. Take a look at the active record association docs.
For named scope, try starting here: railscasts.com/episodes/108-named-scope

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.