获取关联记录数小于某个数字的所有记录

时间:2016-02-12 06:44:45

标签: ruby-on-rails activerecord

我的模型Cleaners在联合表Assignments中有很多Occurrencenumber_of_cleaners模型有一个字段Occurrences

如何使用Active Record(或SQL,Postgres)找到所有Cleaners,其中分配的occurrences.number_of_cleaners数量小于Occurrences中指定的数量?

此查询用于标识Cleaners,我们需要在其中找到更多Occurrence以分配给class Occurrence < ActiveRecord::Base belongs_to :job has_many :assignments has_many :cleaners, through: :assignments end class Assignment < ActiveRecord::Base belongs_to :cleaner belongs_to :occurrence end

Occurrence

作为旁注,我们之前只是查询了Assignment的{​​{1}},而不管occurrences.number_of_cleaners。查询看起来像这样:

# Select future occurrences which do not have an assignment (and therefore no cleaners) and select one per job ordering by booking time
# The subquery fetches the IDs of all these occurrences
# Then, it runs another query where it gets all the IDs from the subquery and orders the occurrences by booking time
# See http://stackoverflow.com/a/8708460/1076279 for more information on how to perform subqueryes
subquery = Occurrence.future.where.not(id: Assignment.select(:occurrence_id).uniq).select('distinct on (job_id) id').order('occurrences.job_id', 'booking_time')
@occurrences = Occurrence.includes(job: :customer).where("occurrences.id IN (#{subquery.to_sql})").where.not(bundle_first_id: nil).select{ |occurrence| @current_cleaner.unassigned_during?(occurrence.booking_time, occurrence.end_time) }

1 个答案:

答案 0 :(得分:1)

您应该在模型上实现counter_cache,而不是加入表格并进行查询,因为它更有效,并且完全符合此目的。

有关详细信息,请查看以下链接:

Counter Cache in Rails

Three Easy Steps to Using Counter Caches in Rails