Rails: 查找 parents 且 children 没有属性
Rails: find parents with children not having an attribute
- Invoice has_many Item
- Item belongs_to Invoice
我正在尝试查找所有没有处于状态 0、1 或 2 的项目的发票。
示例:
Invoice 1
Items:
Item 1 - status 0
Item 2 - status 8
Invoice 2
Items:
Item 1 - status 6
Item 2 - status 8
查询应该是 return 发票 2,因为它的任何项目都没有在 [0, 1, 2] 中的状态。
我试过了,但没用:
Invoice.includes(:items).where.not(items: { status: [0, 1, 2] })
但它不起作用。它会保留 returning 包含处于禁止状态的项目的发票。
这个查询应该可以解决问题:
Invoice.joins(:items).where("items.status NOT IN (0, 1, 2)")
生成的 SQL 可能类似于:
SELECT "invoices".*
FROM "invoices"
INNER JOIN "items"
ON "items"."invoice_id" = "invoices"."id"
WHERE (items.status NOT IN (1, 2, 3))
- Invoice has_many Item
- Item belongs_to Invoice
我正在尝试查找所有没有处于状态 0、1 或 2 的项目的发票。
示例:
Invoice 1
Items:
Item 1 - status 0
Item 2 - status 8
Invoice 2
Items:
Item 1 - status 6
Item 2 - status 8
查询应该是 return 发票 2,因为它的任何项目都没有在 [0, 1, 2] 中的状态。
我试过了,但没用:
Invoice.includes(:items).where.not(items: { status: [0, 1, 2] })
但它不起作用。它会保留 returning 包含处于禁止状态的项目的发票。
这个查询应该可以解决问题:
Invoice.joins(:items).where("items.status NOT IN (0, 1, 2)")
生成的 SQL 可能类似于:
SELECT "invoices".*
FROM "invoices"
INNER JOIN "items"
ON "items"."invoice_id" = "invoices"."id"
WHERE (items.status NOT IN (1, 2, 3))