gpt4 book ai didi

ruby-on-rails - Active Record Where Not bool 值 : true

转载 作者:数据小太阳 更新时间:2023-10-29 07:51:35 24 4
gpt4 key购买 nike

我正在努力思考 ActiveRecord 查询。

我正在尝试在我的数据库中搜索 ID 为 1..100 的 GolfRetailer 对象,这些对象在其 :website 字段中包含某些内容(不是 nil),并且在他们的 duplicate_domain 字段中没有 true

这是我期望的查询:

GolfRetailer.where.not(网站:nil,duplicate_domain:true).where(id:1..100)

我还尝试了基本相同查询的这种变体:GolfRetailer.where.not(website: nil).where(id: 1..100, duplicate_domain: !true)

但是两者都返回一个空数组,尽管肯定有满足这些要求的记录。

当我运行 GolfRetailer.where.not(website: nil).where(id: 1..100) 时,我得到一个数组,当我运行 GolfRetailer.where.not (website: nil, duplicate_domain: nil).where(id: 1..100) 我也得到一个数组,但是所有记录确实都有真正的 duplicate_domain 标志,这是这不是我要找的。

我不想搜索具有 duplicate_domain: nil 的记录,因为它并不总是正确的(我可能还没有处理它们的域)。

为清楚起见,这里是模型的架构。

create_table "golf_retailers", force: :cascade do |t|
t.string "name"
t.datetime "created_at", null: false
t.datetime "updated_at", null: false
t.string "place_id"
t.string "website"
t.string "formatted_address"
t.string "google_places_name"
t.string "email"
t.boolean "duplicate_domain"
t.index ["duplicate_domain"], name: "index_golf_retailers_on_duplicate_domain"
end

要使此查询正常工作,我缺少什么?

最佳答案

发生这种情况是因为在 SQL 中,当您执行 != TRUE 时,任何 NULL 值都不会包含在结果中。这是因为 NULL 值代表一个未知值,所以数据库不知道如何做 comparison operations基于未知值,因此它们被排除在外。

解决这个问题的一种方法是使用 IS DISTINCT FROM :

GolfRetailer
.where(id: 1..100)
.where.not(website: nil)
.where("duplicate_domain IS DISTINCT FROM ?", true)

正如其他人所提到的,您还应该问问自己是否真的不知道 GolfRetailer 是否有 duplicate_domain

如果所有 GolfRetailerduplicate_domainNULL 实际上意味着它们没有 (false) 而不是您应该考虑完全阻止该列的 NULL 值。

您可以通过在带有 change_column database migration 的列上添加 NOT NULL 约束来做到这一点.

为了添加 NOT NULL 约束,您首先需要确保列中的所有数据都具有非空值。

def change
GolfRetailer.in_batches.update_all(duplicate_domain: false)

change_column_null :golf_retailers, :duplicate_domain
end

如果您的应用程序处于负载之下,您还应该注意任何此类迁移可能具有的潜在性能 - 特别是如果您添加具有默认值的 NOT NULL 约束。

考虑使用类似 Strong Migrations 的东西gem 帮助查找可能导致生产前停机的数据库迁移。

关于ruby-on-rails - Active Record Where Not bool 值 : true,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55361017/

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