我正在尝试创建一个范围来返回介于特定范围和日期之间的所有记录。
我有一个方法来完成这个,但我正在尝试重构它。
原始方法:
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}}
... ^
甚至可以在范围内使用条件吗?我还没弄清楚。
答案 0 :(得分:1)
没有运算符=<
(不仅是未定义的,而且是非法的)。您可能打算<=
。
如何记忆:
=>
保留用于散列文字并用于接收rescue
中的错误。因此,“等于或大于”不能表达。它由>=
表示。>=
,您希望<=
(而不是=<
)为“等于或小于”。答案 1 :(得分:0)
看起来你有语法错误。你应该在where块中使用括号而不是花括号。
> df <- data.frame(Crime = c("a", "b", "c"), freq = c(30, 15, 10))
> df
|Crime | freq|
|:-----|----:|
|a | 30|
|b | 15|
|c | 10|
>df[,2] <- df[,2]/8.15
>df
|Crime | freq|
|:-----|--------:|
|a | 3.680982|
|b | 1.840491|
|c | 1.226994|