class User default_scope -> { where(deleted_at: nil) }endclass Order belongs_to :userend
我希望获得已删除或未删除用户的订单:
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 1Order.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) }总结
以上是内存溢出为你收集整理的ruby-on-rails – 如何在join / eager_load中取消验证default_scope?全部内容,希望文章能够帮你解决ruby-on-rails – 如何在join / eager_load中取消验证default_scope?所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)