我尝试使用#645中引入的有条件的第二度has_many ... through
关系,但收效甚微。
就我而言:
has_many :user_assigned_content_skills, -> { where(source: 'user') }, class_name: "ContentSkill"
belongs_to :skill
和belongs_to :course
然后Course.ransack({user_assigned_content_skills_skill_name_not_cont: 'ruby'}).result.to_sql
返回以下内容:
"SELECT courses.* FROM courses LEFT OUTER JOIN content_skills ON content_skills.course_id = courses.id AND content_skills.source = 'user' LEFT OUTER JOIN skills ON skills.id = content_skills.skill_id WHERE (skills.name NOT ILIKE '%ruby%')"
如果课程有多个content_skills,则表示误报。任何想法如何检索与给定技能名称无关的所有课程?
非常感谢任何见解!
答案 0 :(得分:1)
您可以获取与给定技能名称相关联的课程ID,然后获取包含与之前找到的ID不匹配的ID的课程列表。您甚至可以将其作为一个复合SQL查询。
Course.where.not(id: Course.ransack({user_assigned_content_skills_skill_name_cont: 'ruby'}).result)
这将生成如下的SQL:
SELECT courses.*
FROM courses
WHERE courses.id NOT IN (
SELECT courses.id FROM courses
LEFT OUTER JOIN content_skills ON content_skills.course_id = courses.id AND content_skills.source = 'user'
LEFT OUTER JOIN skills ON skills.id = content_skills.skill_id
WHERE (skills.name ILIKE '%ruby%')
)