Find all records that have a counter greater than zero

I'm trying to do something that, in my opinion, would be simple, but it seems that it is not.

I have a project model that has many vacancies.

class Project < ActiveRecord::Base has_many :vacancies, :dependent => :destroy end 

I want to get all projects that have at least 1 vacancy. I tried something like this:

 Project.joins(:vacancies).where('count(vacancies) > 0') 

but he says

SQLite3::SQLException: no such column: vacancies: SELECT "projects".* FROM "projects" INNER JOIN "vacancies" ON "vacancies"."project_id" = "projects"."id" WHERE ("projects"."deleted_at" IS NULL) AND (count(vacancies) > 0) .

+89
sql ruby-on-rails activerecord ruby-on-rails-3
Nov 25 '13 at 2:01
source share
5 answers

joins uses an internal join by default, so using Project.joins(:vacancies) will actually return projects that have a related vacancy.

UPDATE:

As pointed out by @mackskatz in the comment, without a group suggestion, the code above will return duplicate projects for projects with more than one vacancy. To remove duplicates, use

 Project.joins(:vacancies).group('projects.id') 
+57
Nov 25 '13 at 2:48
source share

1) To receive projects with at least 1 vacancy:

 Project.joins(:vacancies).group('projects.id') 

2) To receive projects with more than 1 vacancy:

 Project.joins(:vacancies).group('projects.id').having('count(project_id) > 1') 

3) Or, if the Vacancy model sets a cache counter:

 belongs_to :project, counter_cache: true 

then this will work too:

 Project.where('vacancies_count > ?', 1) 

An exception rule for Vacancy might need to be specified manually ?

+150
Jan 05 '15 at 1:37
source share

Yes, vacancies not a field in a join. I believe you want:

 Project.joins(:vacancies).group("projects.id").having("count(vacancies.id)>0") 
+29
Nov 25 '13 at 2:13
source share
 # 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') 
+14
Jun 02 '17 at 0:32
source share

The error tells you that jobs are not a column of projects, basically.

This should work

 Project.joins(:vacancies).where('COUNT(vacancies.project_id) > 0') 
-6
Nov 25 '13 at 22:48
source share



All Articles