2016-02-12 82 views
0

我有一個模型Occurrence,它有很多Cleaners通過聯合表AssignmentsOccurrence型號的字段爲number_of_cleaners獲取關聯記錄數量小於特定數量的所有記錄

如何使用Active Record(或SQL,Postgres)找到所有Occurrences,其中分配的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不管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) } 
+0

你需要根據這個數字的是發生的所有清潔劑,或者你需要所有出現? – Sravan

+0

我需要所有的事件 – migu

回答

相關問題