如何对计算出的值排序? [英] How can I sort on a calculated value?

查看:77
本文介绍了如何对计算出的值排序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在建立一个NFL Pick'em联赛网站.我有一个用户模型,一个游戏模型和一个联接表,该表捕获了每个用户的个人选择.游戏模型具有结果"属性,该属性包括"W"代表胜利,"L"代表损失,"P"代表推动(并列).

I'm currently building an NFL pick'em league site. I have a Users model, a Games model, and join table which captures each user's individual picks. The games model has a "result" attribute which either consists of "W" for win, "L" for loss, "P" for push (tie).

我在建立排名页面时遇到了问题.目前,我的用户模型中有两种方法:

I am running into issues building a standings page. I currently have two methods in my Users model:

def correct_games
  self.games.where(result: "W").count 
end

def total_games
  self.games.where('result != ?', "P").count 
end

correct_games方法计算用户的正确选择. total_games方法计算游戏总数(不计算导致推送的游戏).

The correct_games method counts the user's picks that were correct. The total_games methods counts the number of total games (not counting games that resulted in a push).

然后在我看来,我目前为每个用户使用的内容:<%= number_to_percentage(current_user.correct_games.to_f / current_user.total_games) %>

Then in my view I currently have for each user: <%= number_to_percentage(current_user.correct_games.to_f / current_user.total_games) %>

该除法为我提供了用户的获胜百分比(#个正确/总选择数).对于我的排行榜,我非常希望获得获胜百分比的降序.问题是,似乎唯一的解决方案是使用.order方法,该方法通常要求数据库中已经存在一些属性,然后您可以在控制器中调用该属性.

This division gives me that user's win percentage (# correct/total picks). For my standings table, I obivously want a descending order on win percentage. The issue is the only solutions to sorting seem to be using the .order method which usually requires some attribute to already be in the database which you can then call in the controller.

我也尝试过将赢率百分比属性添加到数据库中,但是我似乎无法弄清楚每当游戏结果更新时都会更新用户得分的回调.

I've also tried adding this win percentage attribute to the database, but I can't seem to figure out a callback that will update the User's score whenever the game results are updated.

对在视图中计算出的属性进行排序的任何解决方案,或将胜率添加到用户模型的方法?

Any solutions to either sorthing on an attribute that is calculated in the view or a way to add this win percentage to the users model?

提前谢谢!

推荐答案

为什么不只是在模型中而不是在视图中进行计算?添加类似这样的另一种方法:

Why not just do the calculation in the model instead of in the view? Add another method like this:

此代码适用于您的用户模型:

This code goes in your User model:

def percentage_correct
  ((self.correct_games.to_f / self.total_games) * 100).to_i
end

def self.sorted_by_percentage_correct
  User.all.sort_by(&:percentage_correct).reverse
end

这是您在视图中使用它的方式:

This is how you use it in your view:

<% User.sorted_by_percentage_correct.each do |u| %>
  <div><%= u.name %> has pick percentage of <%= u.percentage_correct %>%</div>
<% end %>

这篇关于如何对计算出的值排序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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