在 Rails 查询中使用大于小于时出现语法错误
User.where(is_individual: true)
.includes(:visitor)
.where(visitors: { finished: false })
.where(visitors: { step > 2 })
我试图摆脱上面的查询,但它返回一个错误
syntax error, unexpected '}', expecting =>)
...visitors: { step > 2 })
,但如果我按照下面的方式执行,那么它会起作用。
User.where(is_individual: true)
.includes(:visitor)
.where(visitors: { finished: false })
.where(visitors: { step: 2 })
因此查询不适用于大于运算符。
我什至尝试了下面的查询,但它仍然不起作用
User.where(is_individual: true)
.includes(:visitor)
.where(visitors: { finished: false })
.where(visitors: { "step > ?", 2 })
User.where(is_individual: true)
.includes(:visitor)
.where(visitors: { finished: false })
.where(visitors: { step > 2 })
I am trying to get the out of the above query but it is returning an error
syntax error, unexpected '}', expecting =>)
...visitors: { step > 2 })
But if I do as below then it works.
User.where(is_individual: true)
.includes(:visitor)
.where(visitors: { finished: false })
.where(visitors: { step: 2 })
So the query doesn't work with greater than operator.
I even tried below query and it still doesn't work
User.where(is_individual: true)
.includes(:visitor)
.where(visitors: { finished: false })
.where(visitors: { "step > ?", 2 })
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
您遇到的语法错误是由于传递给最后一个
where
子句的参数结构所致 -{ "step > ?", 2 }
不是一个有效的 Ruby 对象。如果使用 Ruby 2.6 或更高版本,您可以利用其 无限范围语法 构建查询:
如果使用 Ruby 2.5 或更低版本,您可以使用
Float::INFINITY
生成相同的查询:或者,您可以将 SQL 字符串传递到
where
查询包含的模型(您需要通过 references 引用关联表):在这种情况下,您还可以显式使用
joins
来检索所需的结果:The syntax error you're running into is due to the structure of the argument being passed to the last
where
clause -{ "step > ?", 2 }
is not a valid Ruby object.If using Ruby 2.6 or greater, you can leverage its endless range syntax to construct the query:
If using Ruby 2.5 or below you can produce the same query using
Float::INFINITY
:Alternatively, you can pass a SQL string to
where
to query on the included model (you'll need to reference the associated table via references):You can also explicitly use
joins
in this case to retrieve the desired results: