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
相关文章