Reputation: 467
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?
Upvotes: 0
Views: 59
Reputation: 36860
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 %>
Upvotes: 2