Emre Emre - 5 months ago 8
Ruby Question

Ruby loop over the dates

Hello I have Schedules table like this;

<ActiveRecord::Relation [#<Schedule id: 427, date: "2016-06-15", notes: nil, price: "350", promo: "", status: "available", boat_id: 45, created_at: "2016-06-09 19:43:15", updated_at: "2016-06-09 19:43:15">, #<Schedule id: 428, date: "2016-06-16", notes: nil, price: "350", promo: "", status: "available", boat_id: 45, created_at: "2016-06-09 19:43:15", updated_at: "2016-06-09 19:43:15">, #<Schedule id: 429, date: "2016-06-17", notes: nil, price: "350", promo: "", status: "available", boat_id: 45, created_at: "2016-06-09 19:43:15", updated_at: "2016-06-09 19:43:15">, #<Schedule id: 430, date: "2016-06-22", notes: "", price: "253", promo: "", status: "available", boat_id: 3, created_at: "2016-06-14 09:23:55", updated_at: "2016-06-14 09:23:55">, #<Schedule id: 431, date: "2016-06-23", notes: "", price: "253", promo: "", status: "available", boat_id: 3, created_at: "2016-06-14 09:23:55", updated_at: "2016-06-14 09:23:55">]


and user inputs "from" and "to" dates. Lets say I have variables such

a = "2016-06-16".in_time_zone('UTC')
b = "2016-06-19".in_time_zone('UTC')


I would like to loop over Schedule table between these dates (a and b) and get the sum of prices..

I think of a such solution that, I can say;

a = "2016-06-16".in_time_zone('UTC')
b = "2016-06-19".in_time_zone('UTC')
schedules = Schedule.all
price = 0

dates = []
while a < b do
dates << a
a += 1.day
end


Then;

dates.each do |date|
schedules.each do |schedule|
if (date == schedule.in_time_zone('UTC'))
price += schedule.price.to_i
end
end
end


but do not know if that is the most convenient way to do. Thank you

Answer

Why not taking the advantage of DB native implementations. You can do it in SQL.

date_from = "2016-06-16".in_time_zone('UTC')
date_to   = "2016-06-19".in_time_zone('UTC')

Schedule
  .where(date: date_from..date_to) # sql BETWEEN operator
  .sum("price") # SQL aggregate function.