我的模型Voting
与另一个模型has_many
有GroupVoting
关系。表格如下所示:
Voting GroupVoting
- id - id
- voting_id
- party_id
- yes [int]
- no [int]
- abstain [int]
- absent [int]
我的问题是:我应该写什么查询来获取甲方有N
投票“是”的所有投票,另一方有M
投票“否”,第三派对......依此类推?(我们获得派对ID,计票类型和最低投票数)
到目前为止,我的代码如下所示:
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
并且相应的sql查询如下所示:
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
此代码似乎有效但结果是以下形式:
{11666=>3, 11667=>3, 1835=>3}
我希望它的形式为:
ActiveRecord[Voting..., Voting..., ...]
提前谢谢你。 :)
答案 0 :(得分:0)
您的子句末尾有一个count
,不会返回对象,而是count
每个id
。删除它,你应该恢复对象。