I currently have a method that checks if the store is open. It's working nicely, however on the main page I have quite a few stores. Whom again have different locations. Each of these locations again have opening hours.
Now I'm not particularly good with SQL and DB querying and Skylight is complaining and telling me this can most likely be optimized. However I have no clue how.
This is taken from my
has_many :business_hours, through: :locations ... def open? if current_business_hour true else false end end def current_business_hour(current_time: Time.current) business_hours.where('week_day = ? AND open_at <= ? AND close_at >= ?', current_time.wday, current_time.to_s(:time), current_time.to_s(:time)).first end
I'm using Postgres. Now the code should be quite straight forward. I'm looking for business hours that match the current day, and that have a business hour that fits within the current time frame.
SELECT "business_hours".* FROM "business_hours" INNER JOIN "locations" ON "business_hours"."location_id" = "locations"."id" WHERE "locations"."store_id" = ? AND (week_day = ? AND open_at <= ? AND close_at >= ?) ORDER BY week_day LIMIT ?
I'm being notified that:
Skylight detected that this SQL query was repeated multiple times in a single request, which had a significant impact on its response time.
The stores are being rendered like this on a page:
<ul><%= render @stores %></ul>
_store.html.erb looks like this:
<% if store.open? %> <li style="background-image: url(<%= store.header.url %>);"> <%= link_to store_path(store) do %> <h3><b><%= store.name %></b>, <%= store.city.name %></h3> <p class="open-store-text">Open</p> <% end %> </li> <% else %> <li style="background-image: url(<%= store.header.url %>);" class="store-closed"> <%= link_to store_path(store) do %> <h3><b><%= store.name %></b>, <%= store.city.name %></h3> <% end %> <p class="closed-store-text">Closed</p> </li> <% end %>
Now my goal is to try and improve this.