I\'m trying to do something that I thought it would be simple but it seems not to be.
I have a project model that has many vacancies.
class Project &
# None
Project.joins(:vacancies).group('projects.id').having('count(vacancies) = 0')
# Any
Project.joins(:vacancies).group('projects.id').having('count(vacancies) > 0')
# One
Project.joins(:vacancies).group('projects.id').having('count(vacancies) = 1')
# More than 1
Project.joins(:vacancies).group('projects.id').having('count(vacancies) > 1')
In Rails 4+, you can also use includes or eager_load to get the same answer:
Project.includes(:vacancies).references(:vacancies).
where.not(vacancies: {id: nil})
Project.eager_load(:vacancies).where.not(vacancies: {id: nil})
You can also use EXISTS
with SELECT 1
rather than selecting all the columns from the vacancies
table:
Project.where("EXISTS(SELECT 1 from vacancies where projects.id = vacancies.project_id)")
Yeah, vacancies
is not a field in the join. I believe you want:
Project.joins(:vacancies).group("projects.id").having("count(vacancies.id)>0")