Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I sort on a calculated value?

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

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).

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

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?

Thanks in advance!

like image 711
EGD Avatar asked Oct 14 '12 03:10

EGD


1 Answers

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 %>
like image 79
weexpectedTHIS Avatar answered Sep 22 '22 15:09

weexpectedTHIS