本文介绍了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:按关联排序
发布评论