我試圖創建一個作用域來返回落在特定範圍和日期之間的所有記錄。使用AND條件和之間的Rails作用域
我有完成此方法,但我試圖重構它。
原始的方法:
def self.find_by_time facility_id, start_time_string
day_of_week = start_time_string.to_date.wday
start_time= start_time_string.to_datetime.strftime("%H:%M")
self
.where("facility_id = ? AND (? BETWEEN start_day AND end_day) AND (? BETWEEN start_time AND end_time)",
facility_id, day_of_week, start_time)
end
這工作得很好,但我不喜歡這裏的使用SQL,我想使用範圍和squeel把它清理乾淨。我還希望直接傳遞Facility對象而不是僅僅傳入id。
這就是我想:
scope :within_weekday, -> (weekday) {where {start_day <= weekday} & {end_day >= weekday}}
scope :within_time, -> (time) {where {start_time <= time} & {end_time >= time}}
def self.find_by_time facility, start_time
day_of_week = start_time_string.to_date.wday
start_time= start_time_string.to_datetime.strftime("%H:%M")
self.find_by(facility: facility).within_date(day_of_week).within_time(start_time).first
end
一些錯誤,我越來越:
SyntaxError: /vagrant/playtoday/app/models/pricing_period.rb:12: syntax error, unexpected '}', expecting =>
...weekday} & {end_day >= weekday}}
... ^
/vagrant/playtoday/app/models/pricing_period.rb:13: syntax error, unexpected '}', expecting =>
...e <= time} & {end_time >= time}}
... ^
它甚至有可能使用範圍的條件?我還沒有弄清楚。
這是一個粗心的錯誤,但我仍然不幸工作。我更新了OP以顯示錯誤 – Batman