我如何在Rails中计算工人表中的总票数?[英] How I can count the total votes in worker table in Rails

本文是小编为大家收集整理的关于我如何在Rails中计算工人表中的总票数?的处理方法,想解了我如何在Rails中计算工人表中的总票数?的问题怎么解决?我如何在Rails中计算工人表中的总票数?问题的解决办法?那么可以参考本文帮助大家快速定位并解决问题。

问题描述

当我尝试在 rails 的投票表中计算总票数时,我感到很困惑.

serviceproviders has_many votes
votes belongs_to serviceproviders

我试过这样:

sp = Serviceprovider.joins(:votes).group_by(&:id).count

但它没有得到正确的输出.

我想要的示例输出是:

如果 Jhon Doe 表中有 5 行投票,我在查询时可以获得总共 5 票.任何人都可以告诉我如何执行查询.谢谢!

更新:

感谢您的回答.

我在我的 rails c 中试过这个.

vote = Vote.joins(:serviceprovider).group(:serviceprovider_id).count

我得到了结果:{108=>2, 109=>1}

我的问题是如何获得前 10 名的最高票数?

推荐答案

这是表格:

app_development=# select * from votes;

 id |  city   |         created_at         |         updated_at         | service_provider_id
----+---------+----------------------------+----------------------------+---------------------
  1 | B\'lore  | 2015-02-19 17:35:58.061324 | 2015-02-19 17:35:58.083479 |                   3
  2 | Kol     | 2015-02-19 17:35:58.103013 | 2015-02-19 17:35:58.123405 |                   2
  3 | Mum     | 2015-02-19 17:35:58.11242  | 2015-02-19 17:35:58.125345 |                   2
  4 | Kochin  | 2015-02-19 17:35:58.136139 | 2015-02-19 17:35:58.167971 |                   1
  5 | Mum     | 2015-02-19 17:35:58.145833 | 2015-02-19 17:35:58.170319 |                   1
  6 | Chennai | 2015-02-19 17:35:58.156755 | 2015-02-19 17:35:58.171996 |                   1
(6 rows)

app_development=# select * from service_providers;

 id | name |         created_at         |         updated_at
----+------+----------------------------+----------------------------
  1 | MTS  | 2015-02-19 17:35:57.837508 | 2015-02-19 17:35:57.837508
  2 | HCL  | 2015-02-19 17:35:57.923479 | 2015-02-19 17:35:57.923479
  3 | ACL  | 2015-02-19 17:35:57.934414 | 2015-02-19 17:35:57.934414

您需要以下查询才能获得所需的结果:

Vote.joins(:service_provider)
    .group(:service_provider_id)
    .order("count_all desc")
    .limit(10)
    .count

在 Rails 中测试控制台:

[arup@app]$ rails c
Loading development environment (Rails 4.1.1)
[1] pry(main)> Vote.joins(:service_provider).group(:service_provider_id).order("count_all desc").limit(2).count
   (2.0ms)  SELECT  COUNT(*) AS count_all, service_provider_id AS service_provider_id FROM "votes" INNER JOIN "service_providers" ON "service_providers"."id" = "votes"."service_provider_id" GROUP BY service_provider_id  ORDER BY count_all desc LIMIT 2
=> {1=>3, 2=>2}
[2] pry(main)>

本文地址:https://www.itbaoku.cn/post/1764115.html