I need to sort league table in Rails 3, so I have LeagueTable model, Team model and Match model.
Basic sorting is done by points summary, so this is easy part. But when two teams got the same points number, I want to sort them by points won in matches between this two teams.
I got no idea how to do this.
EDIT:
# league_table.rb model
class LeagueTable < ActiveRecord::Base
belongs_to :team
end
# match.rb model
class Match < ActiveRecord::Base
belongs_to :team_home, :class_name => "Team"
belongs_to :team_away, :class_name => "Team"
end
# team.rb model
class Team < ActiveRecord::Base
has_many :matches
end
# schema.rb
create_table "league_tables", :force => true do |t|
t.integer "team_id"
t.integer "points"
t.integer "wins"
t.integer "draws"
t.integer "looses"
t.integer "goals_won"
t.integer "goals_lost"
t.datetime "created_at"
t.datetime "updated_at"
t.integer "matches"
t.integer "priority"
end
create_table "matches", :force => true do |t|
t.integer "team_home_id"
t.integer "team_away_id"
t.integer "score_home"
t.integer "score_away"
t.datetime "created_at"
t.datetime "updated_at"
end
create_table "teams", :force => true do |t|
t.string "name"
t.datetime "created_at"
t.datetime "updated_at"
end
Very interesting question. Here is (more less) how I would handle it, using recursion and the magic of
group_by.{team_foo => {:points => 10, :goals_for => 33, :goals_against => 6}, team_bar => {:points => 18, :goals_for => 50, :goals_against => 11}...}.final_order, which is empty now.all_teams_scores.group_by:teams.group_by {|t| all_teams_scores[t][:points]}. What you get is anOrderedHash, looking like:{10 => [team_foo], 18 => [team_bar, team_xyz]}. The key is what you group by, the value is always an array. Store this hash, e.g. asleague_table.league_table(remember to reverse when needed) and check the values ofleague_tableaccording to them. If the array has two or more elements, apply points 3.-5. to the teams in that array. If the array has one element, append this element tofinal_order.Some remarks:
group_byan array (which helps when you want to sort over a number of things before or after you sort by direct games).create viewbased on that and access league table from Rails through it (views are, generally, read only). Of course, removing the access to these fields from the administrative interface is also ok, for 99.99% situations 😉Hope this helps.