0

I have the following associations:

class Shop < ApplicationRecord
  has_many :opening_hours
end

class OpeningHour < ApplicationRecord
  belongs_to :shop
end

I'm looping through shops inside a view like this:

<% @shop.each do |shop|%>
  <%= shop.street %>
  <%= shop.city %>
<% end %>

I have an action inside a controller, from which I want to check if a shop is open or not:

def open
  @open = OpeningHour.where(day: Time.zone.now.wday).where('? BETWEEN opens AND closes', Time.zone.now).any?
end

I would like to show if the shop is open or not with something like this:

<% if %>
  <span style="color: black">Open</span>
<% else %>
  <span style="color: lightgrey">Close</span>
<% end %>

How can I add the above if and else to the loop in order to show if each shop is open or close?

4
  • Is your OpeningHour model not related to Shop? Commented Apr 23, 2018 at 14:37
  • How does your 'open' method know which shop's times to use? Commented Apr 23, 2018 at 14:39
  • Thanks for the reply @16kb I just added the associations of the both models to my original question Commented Apr 23, 2018 at 14:40
  • Thanks for the reply @ SteveTurczyn ! that is exactly what I'm trying to figure out... and how to implement it according to the loop! Commented Apr 23, 2018 at 14:41

1 Answer 1

2

Assuming opening_hours belong to the shop model

class Shop
  def open?
    opening_hours.where(day: Time.zone.now.wday).where('? BETWEEN opens AND closes', Time.zone.now).any?
  end
end

Then in the view

<% if shop.open? %>
    <span style="color: black">Open</span>
<% else %>
    <span style="color: lightgrey">Close</span>
<% end %>
Sign up to request clarification or add additional context in comments.

1 Comment

Beat me to it; Worth pointing out again to the author that these types of methods do NOT belong in controllers but in the models.

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.