如何在Rails的工作表中计算总票数 [英] How I can count the total votes in worker table in Rails
本文介绍了如何在Rails的工作表中计算总票数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
当我尝试计算我的投票表中的总票数时,我感到很困惑。
I'am confused when I try to count the total votes in my votes table in rails..
serviceproviders has_many votes
votes belongs_to serviceproviders
我尝试过这样:
sp = Serviceprovider.joins(:votes).group_by(&:id).count
但它没有得到正确的输出。
but it doesn't get the right output.
我想要的示例输出是:
如果表中Jhon Doe的票数为5行,则当我查询时可以得到5票。谁能给我一个想法,如何执行查询。谢谢!
If in the table Jhon Doe has 5 row of votes in the table, I can get the total 5 votes when I query. Can any give me the idea how can execute the query. Thank you!
更新:
感谢您的回答。
我在c中尝试过此操作。
I tried this in my rails c.
vote = Vote.joins(:serviceprovider).group(:serviceprovider_id).count
我得到的结果是: {108 => ; 2,109 => 1}
我的问题如何获得前10名的最高投票?
My question how can I get the top 10 highest votes?
推荐答案
这是表格:
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
您需要以下查询以获得所需的结果:
You need the following query to obtain the desired result :
Vote.joins(:service_provider)
.group(:service_provider_id)
.order("count_all desc")
.limit(10)
.count
在Rails中经过测试控制台:
Tested in Rails console :
[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)>
这篇关于如何在Rails的工作表中计算总票数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文