尊重高级收集协会的负面条件

时间:2017-01-18 10:32:21

标签: ruby-on-rails ransack

我尝试使用#645中引入的有条件的第二度has_many ... through关系,但收效甚微。

就我而言:

  • 课程has_many :user_assigned_content_skills, -> { where(source: 'user') }, class_name: "ContentSkill"
  • 和ContentSkill belongs_to :skillbelongs_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,则表示误报。任何想法如何检索与给定技能名称无关的所有课程?

非常感谢任何见解!

1 个答案:

答案 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%')
)