-1

I have a list of Flights departing and arriving to an airport. Each Flight has a departure/arrival time. I want to display the list of flights as a timeline with the departures on the left and arrivals on the right, grouped by hours, like this:

     Departures  | Arrivals

Hours 08 - 09

Flight 1, 08:15  | Flight ABC, 08:12
Flight 2, 08:21  | Flight XY, 08:36
Flight 05, 08:49 | Flight ABC, 08:38

Hours 09 - 10

Flight 1, 09:25  | Flight ABC, 09:55
Flight 2, 09:56  | 

....

I am creating the hash like this:

@flights= {}

Flight.each do |t|
  @flights[t_time] ||= []
  t_time = t.departure_date.change(min: 0)
  if t.departure
    @flights[t_time][0] << t #departures
  else
    @flights[t_time][1] << t #arrivals
  end
end

This seems to be working. But I have no clue how to parse this structure in the view to access each time, and after that each object in the two arrays.

halfer
  • 19,824
  • 17
  • 99
  • 186
H Mihail
  • 613
  • 8
  • 18
  • Is there a reason you are not storing the arrival and departure time in the same record of a Flight? – Justin Wood Jul 23 '14 at 15:20
  • It's not the same flight. They are different flights, arrivals and departures. I just want to display them side by side, based on the hour of departure / arrival. – H Mihail Jul 23 '14 at 15:24
  • I'm not going to lie. That would be very confusing to look at. – Justin Wood Jul 23 '14 at 15:25
  • *But I have no clue how to parse this structure in the view to access each time, and after that each object in the two arrays.* -> Come again? – konsolebox Jul 23 '14 at 15:29
  • I don't know how to access individual flights from the hash. I get `undefined method []` – H Mihail Jul 23 '14 at 15:34
  • Your code as it is won't work - it will throw `undefined method << for nil:NilClass` on line `@flights[t_time][0] << t` – Uri Agassi Jul 23 '14 at 16:24
  • I initialized the array earlier after I got that error. Now is working. – H Mihail Jul 23 '14 at 16:36

1 Answers1

0

Finally figured it out. First, I changed the hash and initialized it:

@global_flights[t_time] ||= {}
@global_flights[t_time][:departures] ||= [] # departures
@global_flights[t_time][:arrivals] ||= [] # arrivals

....

Flight.each do |t|
    t_time = t.departure_date.change(min: 0)
    if t.departure
        @global_flights[t_time][:departures] << t
    else
        @global_flights[t_time][:arrivals] << t
    end
end

This allows me in the view to display the data as needed:

<% @global_flights.each do |times, flights| %>
    <%= times %>
    <% flights[:departures].each do |t| %>
        <%= render partial: "flight", locals: {t: t} %>
    <% end %>
    <% flights[:arrivals].each do |t| %>
        <%= render partial: "flight", locals: {t: t} %>
    <% end %>
<% end %>
H Mihail
  • 613
  • 8
  • 18