SQL query complex relay
First of all, the user has a lot of age_demographics. The AgeDemographic object looks like this:
#<AgeDemographic id: 4384, user_id: 799, range: "35 - 49", percentage: 3.2, created_at: "2015-05-22 04:17:10", updated_at: "2015-05-22 04:17:10">
I am creating a user search tool where someone will select multiple age ranges that they want to target (like "12 - 17"
and "18 - 24"
). I need to select users who have a collection of age demographics with a total percentage greater than 50%
.
This is what I started with:
User.joins(:age_demographics).where("age_demographics.range IN (?)", ["12 - 17", "18 - 24", "25 - 34"])
But I can't figure out how to link the sum of the percentages of these age_demographics to this where clause.
Let me know if this doesn't make any sense.
+3
source to share