【发布时间】:2016-05-09 01:37:49
【问题描述】:
我想找到至少有 1 个 variant 且 variant_type = 1 且没有任何 variant 且 variant_type = 2 的 courses。
所以我的查询如下:
Course.where("id IN ( SELECT course_id
FROM course_variants
WHERE variant_type = 1
)
AND id NOT IN (
SELECT course_id
FROM course_variants
WHERE variant_type = 2
)")
另外,一个course 有很多course_variants。
我在 where 子句中使用原始查询,我想使用 Active Record 接口或 Arel 来改进它,有什么解决方案吗?
谢谢!
使用输入更新预期输出
输入
course: {id=1, course_variants: [{variant_type: 1}, {variant_type: 2}]}
course: {id=2, course_variants: [{variant_type: 1}, {variant_type: 3}]}
course: {id=3, course_variants: [{variant_type: 2}, {variant_type: 3}]}
输出
course: {id=2, course_variants: [{variant_type: 1}, {variant_type: 3}]}
【问题讨论】:
-
variant_type可以取什么值?只有 1、2、3 或无限的数字? -
variant_type 是一个枚举,范围值为 [1..4]
-
当你试图用 2 排除
variant_type时,试试这个查询Course.includes(:course_variant).where.not(course_variants: {variant_type: 2}) -
它不能正常工作,因为我还需要 variant_type = 1
标签: ruby-on-rails activerecord arel