Rails 3 ActiveRecord:按关联排序 [英] Rails 3 ActiveRecord: Order by count on association

查看:41
本文介绍了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:按关联排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆