我有以下关联:
class Shop < ApplicationRecord
has_many :opening_hours
end
class OpeningHour < ApplicationRecord
belongs_to :shop
end
我在这样的视图中循环浏览商店:
<% @shop.each do |shop|%>
<%= shop.street %>
<%= shop.city %>
<% end %>
我在控制器内部有一个动作,我想从中检查商店是否开放:
def open
@open = OpeningHour.where(day: Time.zone.now.wday).where('? BETWEEN opens AND closes', Time.zone.now).any?
end
我想用这样的东西来展示商店是否开放:
<% if %>
<span style="color: black">Open</span>
<% else %>
<span style="color: lightgrey">Close</span>
<% end %>
如何将上述if
和else
添加到循环中,以显示每个商店是开放还是关闭?
答案 0 :(得分:2)
假设opening_hours
属于shop
型号
class Shop
def open?
opening_hours.where(day: Time.zone.now.wday).where('? BETWEEN opens AND closes', Time.zone.now).any?
end
end
然后在视图中
<% if shop.open? %>
<span style="color: black">Open</span>
<% else %>
<span style="color: lightgrey">Close</span>
<% end %>