[英]How to check if associated model has entries in Rails 5?
我有一個模型RegularOpeningHour(dayOfWeek: integer)
與模型OpeningTime(opens: time, closes: time)
。 RegularOpeningHour
與OpeningTime
具有1:n的關系,因此特定的一天可以有很多開放時間。
(我知道我可以在RegularOpeningHour中僅包含一個帶有“ opens”和“ closes”的條目,但由於其他原因,我需要進行此拆分)
現在我要open?
-Method,返回是否營業。 我在模型文件normal_opening_hour.rb中嘗試了以下操作:
def open?
RegularOpeningHour.where(dayOfWeek: Time.zone.now.wday).any? { |opening_hour| opening_hour.opening_times.where('? BETWEEN opens AND closes', Time.zone.now).any? }
end
不幸的是,這是行不通的。 有什么解決辦法嗎?
這個怎么樣:
def open?
joins(:opening_times)
.where(dayOfWeek: Time.current.wday)
.where("opens <= :time AND closes >= :time", time: Time.current)
.any?
end
編輯:聯接中缺少':'
由於您具有RegularOpeningHour
與OpeningTime
has_many
關聯, OpeningTime
可以使用如下所示的OpeningTime
查詢:
RegularOpeningHour.joins(:opening_times).where(dayOfWeek: Time.zone.now.wday).where('? BETWEEN opening_times.opens AND opening_times.closes', Time.zone.now).any?
你可以創建一些領域做出選擇開放OpeningTime
S和打開RegularOpeningHour
s以上笨重。 這使得創建給定選擇更加容易。
class OpeningTime < ApplicationRecord
# ...
belongs_to :regular_opening_hour
def self.open
time = Time.current
where(arel_table[:opens].lteq(time).and(arel_table[:closes].gteq(time)))
end
# ...
end
class RegularOpeningHour < ApplicationRecord
# ...
has_many :opening_times
def self.open
where(
dayOfWeek: Time.current.wday,
id: OpeningTime.select(:regular_opening_hour_id).open,
)
end
# ...
end
def open?
RegularOpeningHour.open.any?
end
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.