我想找到courses
至少有 1 variant
与 variant_type
= 1 并且没有任何 variant
与 variant_type
= 2.
所以我的查询是这样的:
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 接口(interface)或 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}]}
最佳答案
您可以稍微调整您的模型关联:
class Course < ActiveRecord::Base
has_many :type_1_variants, class_name: "CourseVariant", -> { where(variant_type: 1) }
has_many :non_type_3_variants, class_name: "CourseVariant", -> { where.not(variant_type: 3) }
end
Course.joins(:type_1_variants, :non_type_3_variants).group(:course_id).having('COUNT(course_variants.id) > 0').having('COUNT(non_type_3_variants_courses.id) > 0')
您可能需要将“non_type_3_variants_courses”替换为 ARel 在进行连接时生成的正确别名(我没有 Rails env atm)
关于ruby-on-rails - 如何将此原始查询转换为事件记录查询接口(interface)或 arel?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37106706/