Search code examples
ruby-on-railshaml

Return value from elements in hash of arrays


I have the following data:

{53=> [#<Order:0x007feba4e78050 
       deliver_at: Fri, 14 Jul 2017 09:00:00 MYT +08:00,
       shipping_city: "city name", 
       rider_id: 53>,
       #<Order:0x007feba4e776f0 
       deliver_at: Fri, 14 Jul 2017 10:00:00 
       MYT +08:00,
       rider_id: 53, 
       shipping_city: "city name">], 
71=>  [....],[....]} # elements are the same except for the values

This is how I get the data in the controller.

@start_time = Date.today.beginning_of_day + 2.hours
@end_time = Date.today.end_of_day + 2.hours
@orders = Order.where(deliver_at: @start_time..@end_time)
                                 .where('rider_id IS NOT ?', nil)
                                 .group_by{|order| order[:rider_id]}

This is in the view.

%thead
  %tr
    %th Name
    %th 8 AM
    %th 9 AM
    %th 10 AM
    %th 11 AM
    %th 12 PM
    %th 1 PM
    %th 2 PM
    %th 3 PM
    %th 4 PM
    %th 5 PM
    %th 6 PM
    %th 7 PM
    %th 8 PM
    %th 9 PM
    %th 10 PM
    %th 11 PM
    %th 12 AM
%tbody
    [email protected] do |rider_id, orders|
      %tr
        %td= rider_id
          - orders.each do |order|
            %td= order.shipping_city if order.within_delivery_hour?(8, 9)
            %td= order.shipping_city if order.within_delivery_hour?(9, 10)
            %td= order.shipping_city if order.within_delivery_hour?(10, 11)
            %td= order.shipping_city if order.within_delivery_hour?(11, 12)

As you can see, I am grouping the data by rider_id. I want to display the order shipping city in the same row according to the rider, but next to each other. If one order is at 8 am, and the next order is at 9 am, they should be displaying next to each other.

At the moment I got the first order at 8 am, but the next one at 5 boxes after the first one, which will display not at 9 am.

How do I arrange the data I got in the controller to display it correctly? Something that I am missing ?

I apologize if the title is somehow not the correct way to ask, I guess it just shows that I need help. Please let me know if more information is needed. Thank you all!


Solution

  • Thanks to a friend, the problem lies within iterating the orders obtained form the query.

    - @orders.each do |rider_id, orders|
    

    The orders here should be joined and mapped together and the code should be directly under the first iteration which will make it look like:

    - @orders.each do |rider, _orders|
      - orders = Order.joins(:user).where(id: _orders.map(&:id))
    

    Thank you.