问题
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')
回答1:
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.
来源:https://stackoverflow.com/questions/10526012/order-players-on-the-sum-of-their-association-model