我的模型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
我怎么能这样做?
答案 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)"
}