I have a model Voting
that has a has_many
relation to another model GroupVoting
. The tables look like this:
Voting GroupVoting
- id - id
- voting_id
- party_id
- yes [int]
- no [int]
- abstain [int]
- absent [int]
My question is this: What query should I write to fetch all votings on which a party A has N
votings "yes" and another party has M
votes "no", third party... and so on? (We are given the party ids, the vote type to count and the minimum vote count)
So far my code looks like this:
gv = GroupVoting.arel_table
Voting.joins(:group_votings)
.where(
(gv[:party_id].eq(9).and(gv[:yes].gt(30)))
.or(gv[:party_id].eq(115).and(gv[:yes].gt(80)))
.or(gv[:party_id].eq(16).and(gv[:no].gt(60))))
.group("voting_id").having("count(*)>2").count
and the corresponding sql query looks like this:
SELECT COUNT(*) AS count_all, voting_id AS voting_id FROM "votings"
INNER JOIN "group_votings" ON "group_votings"."voting_id" = "votings"."id"
WHERE ((("group_votings"."party_id" = 9 AND "group_votings"."yes" > 25 OR "group_votings"."party_id" = 115 AND "group_votings"."yes" > 60) OR "group_votings"."party_id" = 16 AND "group_votings"."no" > 30))
GROUP BY voting_id HAVING count(*)>2
This code seems to work but the result is in the form of:
{11666=>3, 11667=>3, 1835=>3}
And I want it in the form of:
ActiveRecord[Voting..., Voting..., ...]
Thank you in advance. :)