如何使用符号查询比较运算符

vin*_*nce 0 postgresql activerecord ruby-on-rails ruby-on-rails-6

我目前可以做到这一点

Enrollment.where('starts_at < ?', Time.current)
Run Code Online (Sandbox Code Playgroud)

因为我可以做到这一点

Enrollment.where(starts_at: Time.current)
Run Code Online (Sandbox Code Playgroud)

有没有办法对比较运算符使用相同的格式?我认为其中之一会起作用,但它们不起作用

Enrollment.where(starts_at: "< #{Time.current}")
Run Code Online (Sandbox Code Playgroud)

或者

Enrollment.where('starts_at <': Time.current)
Run Code Online (Sandbox Code Playgroud)

能够做这样的事情真的很棒

Enrollment.where(state: :active, 'starts_at <': Time.current)
Run Code Online (Sandbox Code Playgroud)

max*_*max 5

Rails 没有内置的方式*来使用哈希语法创建小于/大于条件。您可以使用无限范围来创建大于或等于:

adults = Citizen.where(age: 18..)
Run Code Online (Sandbox Code Playgroud)

Rails 6.1开始,您可以使用 beginless 范围来创建小于或等于:

minors = Citizen.where(age: ..17)
Run Code Online (Sandbox Code Playgroud)

但是,如果您需要 LT 而不是 LTE,创建所需的查询实际上非常简单:

Enrollment.where(state: :active)
          .where('starts_at < ?', Time.current)
Run Code Online (Sandbox Code Playgroud)

您还可以使用 Arel:

Enrollment.where(state: :active).where(
  Enrollment.arel_table[:starts_at].lt(Time.current)
)
Run Code Online (Sandbox Code Playgroud)

* 在撰写本文时,请参阅@Yakov 对建议功能的回答


Yak*_*kov 5

此功能可能在 Rails 6.1 中可用。

Enrollment.where('starts_at <': Time.current)
Run Code Online (Sandbox Code Playgroud)

还在讨论: