Rails ActiveRecord按联接表关联计数排序

编程入门 行业动态 更新时间:2024-10-28 15:30:20
本文介绍了Rails ActiveRecord按联接表关联计数排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我有一个资源模型,该模型可以使用使行为成为现实宝石( Github页面)。投票系统运行良好,但是我试图显示按每个资源拥有多少个投票排序的页面。

I have a Resource model that can be voted on using the "Acts As Votable" gem (Github page). The voting system works perfectly but I am trying to display pages ordered by how many votes each Resource has.

当前,我的控制器根据标签提取资源,但未排序:

Currently my controller pulls Resources based on tags and aren't ordered:

@resources = Resource.where(language_id: "ruby")

如果我使用单个资源并致电 @ resource.votes.size将返回它具有多少票。但是,投票是另一张桌子,因此我认为需要进行某种形式的加入,但我不确定如何去做。我需要的是一个很好排序的 ActiveRecord 集合,我可以这样显示吗?

If I take an individual resource and call "@resource.votes.size" it will return how many votes it has. However, votes is another table so I think some sort of join needs to be done but I have not sure how to do it. What I need is a nice ordered ActiveRecord collection I can display like this?

书名-19票

Book name - 19 votes

书名-15票

书名-9票

书名-8票

推荐答案

尝试以下:

@resources = Resouce.select("resources.*, COUNT(votes.id) vote_count") .joins(:votes) .where(language_id: "ruby") .group("resources.id") .order("vote_count DESC") @resources.each { |r| puts "#{r.whatever} #{r.vote_count}" }

包含0的资源投票,使用外部联接。如果下面的示例不起作用,则必须更改joins语句以跨正确的关系进行联接。

To include resources with 0 votes, use an outer join. If the example below doesn't work as is you'll have to alter the joins statement to join across the correct relations.

@resources = Resource.select("resources.*, COUNT(votes.id) vote_count") .joins("LEFT OUTER JOIN votes ON votes.votable_id = resources.id AND votes.votable_type = 'Resource'") .where(language_id: "ruby") .group("resources.id") .order("vote_count DESC")

更多推荐

Rails ActiveRecord按联接表关联计数排序

本文发布于:2023-10-17 11:15:55,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1500732.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:Rails   ActiveRecord

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!