我有两个型号:
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”用户“.”deleted_at“IS NULL”添加到join语句中.
如果我指定关联范围,则没有任何变化:
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,但不确定Rails 4.
User.unscoped { Order.joins(:user) }