Find all records which have a count of an association greater than zero

后端 未结 10 1652
北海茫月
北海茫月 2020-11-30 17:45

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 &         


        
10条回答
  •  南笙
    南笙 (楼主)
    2020-11-30 18:10

    1) To get Projects with at least 1 vacancy:

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

    2) To get Projects with more than 1 vacancy:

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

    3) Or, if Vacancy model sets counter cache:

    belongs_to :project, counter_cache: true
    

    then this will work, too:

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

    Inflection rule for vacancy may need to be specified manually?

提交回复
热议问题