有没有办法反转 ActiveRecord::Relation 查询?
假设我们有以下内容:
irb> Post.where(:hidden => true).to_sql
=> "SELECT `posts`.* FROM `posts` WHERE posts.hidden = 1"
我们能否以某种方式从中获得反向 SQL 查询?
我正在寻找的内容可能应该如下所示:
irb> Post.where(:hidden => true).invert.to_sql
=> "SELECT `posts`.* FROM `posts` WHERE NOT (posts.hidden = 1)"
Let's say we have the following:
irb> Post.where(:hidden => true).to_sql
=> "SELECT `posts`.* FROM `posts` WHERE posts.hidden = 1"
Could we somehow get an inverted SQL query out of it?
What I am looking for, should probably look like this:
irb> Post.where(:hidden => true).invert.to_sql
=> "SELECT `posts`.* FROM `posts` WHERE NOT (posts.hidden = 1)"
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(6)
使用不同的语法,是的。例子:
With a different syntax, yes. Example:
在 Rails 4 中,有用于此目的的
not
后缀:在 Rails 3 中,您可以使用 squeel gem< /a>.它提供了许多有用的功能。用它你可以写:
In rails 4 there is
not
suffix for this purpose:In rails 3 you can use squeel gem. It gives many usefull features. And with it you can write:
我们可以进一步采用 Zabba 的回答通过将反向查询传递回 ActiveRecord:
这将返回 ActiveRecord 对象,正如您通常所期望的那样。
We can take Zabba's answer further by passing the inverted query back into ActiveRecord:
This will return ActiveRecord objects, as you would normally expect.
invert_where (Rails 7+)
从 Rails 7 开始,有一个新的 invert_where 方法。
根据文档,它:
来源:
invert_where (Rails 7+)
Starting from Rails 7, there is a new invert_where method.
According to the docs, it:
Sources:
当我查找具有“不真实”条件(例如 false 或 nil)的记录时,我要做的是:
What I do when I'm looking for records with a "not true" condition (eg, false or nil) is:
最后,我们有了 Rails 7 的方法
invert_where
。请检查此提交参考了解更多详情。
Finally we have the method
invert_where
with Rails 7.Please check this commit reference for more details.