Rails 3 ActiveRecord: Order by count on association(Rails 3 ActiveRecord:按关联计数排序)
问题描述
我有一个名为 Song
的模型.我还有一个名为 Listen
的模型.一首Listen
belongs_to :song
,一首歌:has_many listens
(可以听很多次).
I have a model named Song
. I also have a model named Listen
. A Listen
belongs_to :song
, and a song :has_many listens
(can be listen to many times).
在我的模型中,我想定义一个方法 self.top
应该返回最常听的前 5 首歌曲.我如何使用 has_many
关系实现这一点?
In my model I want to define a method self.top
which should return the top 5 songs listened to the most. How can I achieve that using the has_many
relation?
我使用的是 Rails 3.1.
I'm using Rails 3.1.
谢谢!
推荐答案
使用命名范围:
class Song
has_many :listens
scope :top5,
select("songs.id, OTHER_ATTRS_YOU_NEED, count(listens.id) AS listens_count").
joins(:listens).
group("songs.id").
order("listens_count DESC").
limit(5)
Song.top5 # top 5 most listened songs
这篇关于Rails 3 ActiveRecord:按关联计数排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Rails 3 ActiveRecord:按关联计数排序


基础教程推荐
- SQL Server 中单行 MERGE/upsert 的语法 2021-01-01
- SQL Server:只有 GROUP BY 中的最后一个条目 2021-01-01
- 在 VB.NET 中更新 SQL Server DateTime 列 2021-01-01
- SQL Server 2016更改对象所有者 2022-01-01
- 将数据从 MS SQL 迁移到 PostgreSQL? 2022-01-01
- 如何在 SQL Server 的嵌套过程中处理事务? 2021-01-01
- 使用pyodbc“不安全"的Python多处理和数据库访问? 2022-01-01
- 无法在 ubuntu 中启动 mysql 服务器 2021-01-01
- ERROR 2006 (HY000): MySQL 服务器已经消失 2021-01-01
- Sql Server 字符串到日期的转换 2021-01-01