gpt4 book ai didi

ruby-on-rails - Rails where 条件使用 NOT NIL

转载 作者:行者123 更新时间:2023-12-02 13:11:58 30 4
gpt4 key购买 nike

使用 Rails 3 风格,我将如何编写相反的内容:

Foo.includes(:bar).where(:bars=>{:id=>nil})

我想找到 id 不为零的地方。我尝试过:

Foo.includes(:bar).where(:bars=>{:id=>!nil}).to_sql

但这会返回:

=> "SELECT     \"foos\".* FROM       \"foos\"  WHERE  (\"bars\".\"id\" = 1)"

这绝对不是我需要的,而且几乎看起来像是 ARel 中的一个错误。

最佳答案

Rails 4+

ActiveRecord 4.0 及更高版本添加 where.not所以你可以这样做:

Foo.includes(:bar).where.not('bars.id' => nil)
Foo.includes(:bar).where.not(bars: { id: nil })

在处理表之间的范围时,我更喜欢利用 merge这样我就可以更轻松地使用现有范围。

Foo.includes(:bar).merge(Bar.where.not(id: nil))

此外,自 includes并不总是选择连接策略,您应该使用 references也在这里,否则你可能会得到无效的 SQL。

Foo.includes(:bar)
.references(:bar)
.merge(Bar.where.not(id: nil))

rails 3

使用 Rails 3 执行此操作的规范方法:

Foo.includes(:bar).where("bars.id IS NOT NULL")

关于ruby-on-rails - Rails where 条件使用 NOT NIL,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/4252349/

30 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com