简体   繁体   English

Rails-按模型方法结果订购记录

[英]Rails - Ordering records by model method result

I have the User model with the following method: 我有使用以下方法的用户模型:

def like_dislike_proportion
  self.likes.to_f / self.dislikes.to_f
end

Where self.likes and self.dislikes both return an Integer. 如果self.likes和self.dislikes都返回整数。 I want to make a ranking with the top 10 users with the biggest like/dislike proportion, and the bottom 10, with the lowest proportion. 我想对喜欢/不喜欢比例最大的前10个用户和比例最低的后10个用户进行排名。

I tried using 我尝试使用

User.order('like_dislike_proportion DESC').limit(10)

But it doesn't work, because the like_dislike_proportion is not a persistent attribute in the database. 但这是行不通的,因为like_dislike_proportion不是数据库中的持久属性。

How can I solve this? 我该如何解决?

ranking = User.all.map { |u| 
    {name: u.name, proportion: (u.likes.to_f/u.dislikes.to_f)} 
}.sort_by { |r| r[:proportion] } 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM