Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Order Players on the SUM of their association model

I have a database with 6500 players and each player has an average of 15 game results.

Use case

I want to generate a list of players, ordered by the sum of their prize money (a field in the results table). I prefer this to be in some sort of scope, so I can also filter the list on the player's country, etc.

Performance

I have seen posts that mention a cache_counter field for performance. In my case I have thousands of result records (75.000+) so I don't want the calculations being done every time someone visits the generated listings.

Question

What is the best pattern to solve this? And how do I implement it?

Models

class Player < ActiveRecord::Base
  has_many :results
end

class Result < ActiveRecord::Base
  belongs_to :player
end

Schemas

  create_table "players", :force => true do |t|
    t.string   "name"
    t.string   "nationality"
  end

  create_table "results", :force => true do |t|
    t.integer  "player_id"
    t.date     "event_date"
    t.integer  "place"
    t.integer  "prize"
  end

Update

What I am trying to accomplish is getting to a point where I can use:

@players = Player.order_by_prize

and

@players = Player.filter_by_country('USA').order_by_prize('desc')
like image 265
Fred Fickleberry III Avatar asked May 10 '12 00:05

Fred Fickleberry III


People also ask

When all the players of the game follow their optimal strategies?

8. The expected pay off when all the players of the game follow their optimal strategies is known as 'value of the game'.

What are the four types of games in game theory?

Different types of game theory include cooperative/non-cooperative, zero-sum/non-zero-sum, and simultaneous/sequential.

What is a dominant strategy in game theory?

2.1 Dominant strategy. “Dominant strategy” is a term in game theory that refers to the optimal option for a player among all the competitive strategy set, no matter how that player's opponents may play, and the opposite strategy is called “inferior strategy.”

What is Nash equilibrium example?

In the Nash equilibrium, each player's strategy is optimal when considering the decisions of other players. Every player wins because everyone gets the outcome they desire. The prisoners' dilemma is a common game theory example and one that adequately showcases the effect of the Nash equilibrium.


1 Answers

You should be able to use something like this:

class Player
 scope :order_by_prize, joins(:results).select('name, sum(results.prize) as total_prize').order('total_prize desc')  

Refer rails api - active record querying for details.

like image 158
Salil Avatar answered Nov 30 '22 00:11

Salil