在 Rails 范围内使用 AND 条件和 Between

Using AND conditions and Between in Rails Scopes

我正在尝试为 return 特定范围和日期之间的所有记录创建一个范围。

我有一个方法可以完成这个,但我正在尝试重构它。

原始方法:

  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,我想使用 scopes 和 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}}
...                               ^

甚至可以在范围内使用条件吗?我还没弄明白。

没有运算符=<(不仅未定义,而且是非法的)。您可能有意 <=.

如何记忆:

  • 令牌 => 保留用于哈希文字和接收 rescue 中的错误。因此 "equal to or greater than" 不能用那个来表示。表示为>=.
  • 您希望运算符号保持一致;因为有 >=,所以 "equal to or less than".
  • 需要 <=(而不是 =<

看起来你有语法错误。您应该在 where 块中使用圆括号而不是花括号。

scope :within_weekday, -> (weekday) { where { (start_day <= weekday) & (end_day >= weekday) }
scope :within_time, -> (time) { where { (start_time <= time) & (end_time >= time) }