过滤团队的范围取决于成员的年龄

时间:2016-03-22 08:48:21

标签: ruby-on-rails ruby ruby-on-rails-4

我的模型User包含属性:age,模型Team包含has_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

我怎么能这样做?

1 个答案:

答案 0 :(得分: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)"
}