Friday, 6 September 2013

Ordering elements by a field in their belongs_to association

Ordering elements by a field in their belongs_to association

I have Games and Stats. Each Game has_many Stats, and each Stat belongs_to
a Game. I have written code to join all the stats of a particular
Stat_Type (each Stat has a Stat_Type) across each Game for a particular
Athlete, but now I need to order these Stats by their Game's Date field.
Here's a layout of the model associations:
Athlete
-> Games (Date, Opponent, etc)
-> Stats (Name, Value, Game_id, Stat_Type_id, etc)
These are the lines which join the stats I need:
hsh = {}
s_ids = games.map(&:stat_ids)
stats = Stat.joins(:stat_type).where(stats: { id: s_ids }, stat_type: {
id: stat_type_id })
But now I need to order stats by each individual stat's game's date... So
that if I laid them out 1 to 1 by each game they are associated with (and
the games are arranged by date), they will line up properly. How do I do
this?

No comments:

Post a Comment