gpt4 book ai didi

ruby-on-rails - 如何取消 join/eager_load 中的 default_scope?

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

我有两个模型:

class User
default_scope -> { where(deleted_at: nil) }
end

class Order
belongs_to :user
end

我想获得已删除或未删除用户的订单:

Order.joins(:user).merge(User.unscoped)
Order.joins(:user).merge(User.unscope(where: :deleted_at))
# SELECT "orders".* FROM "orders"
# INNER JOIN "users" ON "users"."id" = "orders"."user_id" AND "users"."deleted_at" IS NULL
# ORDER BY "orders"."id" DESC LIMIT 1

Order.eager_load(:user).merge(User.unscoped)
Order.eager_load(:user).merge(User.unscope(where: :deleted_at))
# SELECT "orders"."id" AS t0_r0, "orders"."user_id" AS t0_r1,
# "users"."id" AS t1_r0, "users"."deleted_at" AS t1_r1 FROM "orders"
# LEFT OUTER JOIN "users" ON "users"."id" = "orders"."user_id" AND "users"."deleted_at" IS NULL
# ORDER BY "orders"."id" DESC LIMIT 1

这些都不起作用。

每个查询都将“AND "users"."deleted_at"IS NULL"添加到连接语句中。

如果我指定关联范围,则没有任何变化:

class Order
belongs_to :user, -> { unscoped }
end

但是包括按预期工作:

Order.includes(:user).merge(User.unscoped).last
# SELECT "orders".* FROM "orders" ORDER BY "orders"."id" DESC LIMIT 1
# SELECT "users".* FROM "users" WHERE "users"."id" = 1054

我怎样才能使 rails 取消连接中的关联?

最佳答案

你可以这样试试。它适用于 Rails >= 3

User.unscoped { Order.joins(:user) }

关于ruby-on-rails - 如何取消 join/eager_load 中的 default_scope?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40910488/

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