Rails查询仅在所有has_many的关联均为“ true”的情况下选择父记录

  • labelTimer

  • Sorted S = {0,1,3,4,5,6,8,9} A = [A0,A1,A2] --- A0,A2 -- (Binary,part of subset = 1 not part = 0 ) Index | A0,A2 | Sorted Sum 0 0 0 0 0 1 1 0 0 1 2 0 1 0 3 3 1 1 0 4 4 0 0 1 5 5 1 0 1 6 6 0 1 1 8 7 1 1 1 9 From her we can reverse and find that A0 = S[2^0],A1 = S[2^1],A2 = S[2^2] 页的书

  • 页面具有布尔属性has_many

这样,书号:1条记录可能具有:

  • 第1页,其中belongs_to为真
  • 第2页,read为真
  • 第3页,其中read为假

然后,书号:2为:

  • 第1页,其中read为真
  • 第2页,read为真

通过这种方式,只能从查询中返回图书ID:2。

目前,我有:

read

同时返回图书readBook.includes(:pages).where(pages: {read: true})

如何解决?

sundan308 回答:Rails查询仅在所有has_many的关联均为“ true”的情况下选择父记录

join子句不够用,因为您需要检查来自书本父级的每个read子级的page列值是否为假。

您可以使用where明确添加所需的过滤器:

Book.where.not(id: Page.where(read: false).select(:book_id))

通过在select中使用Page.where(read: false),Rails可以执行单个查询,例如:

SELECT "books".*
FROM "books"
WHERE "books"."id" NOT IN (
  SELECT "pages"."book_id"
  FROM "pages"
  WHERE "pages"."read" = $1
) [["read",false]]
本文链接:https://www.f2er.com/3129011.html

大家都在问