当前 belongs_to ID 但 belongs_to Object 为 Nil 的 ActiveRecord 查询

ActiveRecord Query for Present belongs_to ID but belongs_to Object is Nil

我不太确定如何给它起标题,因为我搜索过的所有内容都为我提供了以下查询的某种形式:Telephone.where(user_id: nil) 这是 而不是 什么我在找

我有两个模型:

Class Telephone < ApplicationRecord
 belongs_to :user, optional: true
end

Class User < ApplicationRecord
 has_one :telephone, dependent: :nullify
end

user object 被销毁时,代码中有一个错误并不总是使 telephone 上的 user_id 无效。我需要清理数据并将所有受影响的 telephonesuser_id 设置为 nil。我编写了以下代码来更新 ~80 telephones,但是在初始查询中有 >400000 条记录得到 returned,因此循环需要很长时间:

telephones = Telephone.where.not(user_id: nil)

telephones.each do |telephone|
  return unless telephone.user.nil?

  telephone.user_id = nil
  telephone.save
end

什么是 Active Record 查询我可以写给 return all telephones 并且 user_iduser object 是零?

下面应该让你的电话有 user_id,但相应的 user 对象是 nil

Telephone.left_outer_joins(:user).where("users.id is NULL AND telephones.user_id is NOT NULL")

您必须在 user 关联上使用 left_joins

Telephone.left_joins(:user).where.not(user: nil).where("users.id": nil)

什么转换为 SQL-查询

SELECT "telephones".* FROM "telephones" LEFT OUTER JOIN "users" ON "users"."id" = "telephones"."user_id" WHERE "telephones"."user_id" IS NOT NULL AND "users"."id" IS NULL