0

I'm trying to loop through an array of the next 7 days, and for each, perform a query to find all the 'Time slots' that match, and add these to an object which I can loop through in my view. This is fairly simple in PHP, but I'm not sure of the syntax in rails. I have a situation where each day can have multiple 'delivery slots' available, and I need to display all these slots for the next week, by day.

So far in my controller I have

d = Date.today
d2 = d + 1.week
@days = (d..d2).to_a
@deliveries = []
@days.each do |d|
  @deliveries[][dayname] = d.strftime("%a")
  @deliveries[][slots] = Model.where("day = ?", d.strftime("%w"))
end

Then in my view, I want to do this

<% @deliveries.each do |d| %>
  <%= d.dayname %>
  <% d.slots.each do |s| %>
    <%= slot data here %>
  <% end %>
<% end %>

Where am I going wrong? Not quite sure of the syntax in rails where you'd use "as key => value" in php. Is this the most efficient way to go about it? It will result in 7 queries which isn't ideal

Thanks for any help

1 Answer 1

2

If your Model only has a day number, the slots will be the same for every week and you could do something like:

slots_by_day = Model.all.group_by(&:day)
@deliveries = (Date.today..Date.today + 6.days).each_with_object({}) do |day, dayname_groups|
  dayname_groups.merge!(day.strftime('%a') => slots_by_day[day.strftime('%w').to_i])
end

It will fetch all models, group them by day number of the week and then build a hash mapping each day number with the day name ending up in a hash like:

=> {"Wed"=>[#<Model...>, #<Model...>, #<Model...>, #<Model...>],
"Thu"=>[#<Model...>, #<Model...>, #<Model...>, #<Model...>], "Fri"=>...}

The hash would be used like this:

<% @deliveries.each do |dayname, slots| %>
  <%= dayname %>
  <% slots.each do |s| %>
    <%= slot data here %>
  <% end %>
<% end %>
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks so much, this looks perfect. But how would I pull the next 7 days in the correct order as I've done with the @days array above? I need to start on the current day, then pull the next 6
@Dave I edited my answer and it will give you a sorted hash as you need now
Perfect! Just needed to wrap the slots.each loop in a conditional <% if !slots.blank? %> - since not all days will have slots but I still want to dispaly them.

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.