使用连接表上的where子句获取记录

时间:2014-07-09 19:05:48

标签: sql ruby-on-rails postgresql arel

我的模型Voting与另一个模型has_manyGroupVoting关系。表格如下所示:

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..., ...]

提前谢谢你。 :)

1 个答案:

答案 0 :(得分:0)

您的子句末尾有一个count,不会返回对象,而是count每个id。删除它,你应该恢复对象。