user1301037 user1301037 - 1 month ago 5
Ruby Question

Rails - open_hours: Looping all days of week even not saved at DB (set as closed)

I have a Venue model that has_many and accept_nested_attributes_for working_hours.

The Working Hour model:

create_table "working_hours", force: :cascade do |t|
t.integer "day"
t.time "open_time"
t.time "close_time"
t.integer "venue_id"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.index ["merchant_id"], name: "index_working_hours_on_merchant_id", using: :btree
end


At my view I create a list to show the open_time and close_time according day of week, as:

<ul class="working-hours-body">
<% @merchant.working_hours.order(:day).each do |wh| %>
<li>
<%= t(:"date.abbr_day_names")[wh.day.to_i] %> :
<%= wh.open_time.to_formatted_s(:hour_and_minutes) %> -
<%= wh.close_time.to_formatted_s(:hour_and_minutes) %>
</li>
<% end %>
</ul>


Supposing I create records for Monday, Tuesday, Wednesday, Thursday, Friday. At the list are showed as:

Monday: 8am - 17pm
Tuesday: 8am - 17pm
Wednesday: 8am - 17pm
Thursday: 8am - 17pm
Friday: 8am - 17pm


What is the best approach to show the Saturday and Sunday as Closed?

Monday: 8am - 17pm
Tuesday: 8am - 17pm
Wednesday: 8am - 17pm
Thursday: 8am - 17pm
Friday: 8am - 17pm
Saturday: closed
Sunday: closed

Answer
<ul class="working-hours-body">
  <% %w(Monday Tuesday Wednesday Thursday Friday Saturday Sunday).each_with_index do |day, index| %>
    <li>
      <% wh = @merchant.working_hours.find_by(day: index) %>
      <% if wh %>
        <%= t(:"date.abbr_day_names")[wh.day.to_i] %> : 
        <%= wh.open_time.to_formatted_s(:hour_and_minutes)  %> -
        <%= wh.close_time.to_formatted_s(:hour_and_minutes)  %> 
      <% else %>
        <%= day %> : Closed
      <% end %>
    </li>
  <% end %>
 </ul>
Comments