2016-03-22 50 views
2

我有一個模特User,屬性:age和模型Teamhas_many: :users根據記憶年齡篩選團隊的範圍

我想知道,如何創建2個示波器:same_ages:different_ages來篩選團隊,或者他們都具有相同的年齡,或者他們有不同的年齡。

Team.same_ages 
# In all teams returned, all members have the same age 

Team.different_ages 
# In all teams returned, there is at least one member with 
# different age as the others 

我怎麼能這樣做?

回答

0

我只是覺得範圍會像:

scope :same_ages, -> { 
    where("id IN (SELECT team_id 
       FROM users 
       GROUP BY team_id 
       HAVING COUNT(DISTINCT(age)) = 1)" 
} 

scope :different_ages, -> { 
    where("id IN (SELECT team_id 
       FROM users 
       GROUP BY team_id 
       HAVING COUNT(DISTINCT(age)) > 1)" 
}