Rails 3 ActiveRecord:按关联排序

编程入门 行业动态 更新时间:2024-10-28 13:15:18
本文介绍了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:按关联排序

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

发布评论

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

>www.elefans.com

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