Reputation: 1366
I have two each loops inside week
loop, static_events, loop_events
creates links that sorted by time.
The problem is when the first loop ends, the second each loop create elements after the first one, and the order breaks.
<% @week.each do |day| %>
<% @static_events.each do |event| %>
<%= link_to event.start_time.strftime('%H:%M'), event_path(event.id) %>
<% end %>
<% @loop_events.each do |event| %>
<%= link_to event.start_time.strftime('%H:%M'), event_path(event.id) %>
<% end %>
<% end %>
The result will be roughly as:
01:00 # => @static_events => index 1
03:00 # => @static_events => index 2
04:00 # => @static_events => index 3
02:00 # => @loop_events => index 1
I need this result:
01:00 # => @static_events => index 1
02:00 # => @loop_events => index 1
03:00 # => @static_events => index 2
04:00 # => @static_events => index 3
How can I order/sort both each loops by time, and achieve the result above?
Upvotes: 0
Views: 131
Reputation: 44581
Well, you can merge them (arrays, not loops, of course) and sort by time:
<% [@static_events, @loop_events].flatten.sort_by(&:start_time).each do |event| %>
<%= link_to event.start_time.strftime('%H:%M'), event_path(event.id) %>
<% end %>
Upvotes: 2