grabury
grabury

Reputation: 5559

How to work with many has many through relationships

I have a system where you can vote for a player that belongs to a team. I also have a placements model that keeps track of the votes and each player's position in a team for a particular month.

class Team < ActiveRecord::Base
  has_many :players, dependent: :destroy
  has_many :placements, through: :players

class Player < ActiveRecord::Base
  belongs_to :team
  has_many :votes, dependent: :destroy
  has_many :placements

class Placement < ActiveRecord::Base
  belongs_to :player
  attr_accessible :month, :player_id, :points, :position

class Vote < ActiveRecord::Base
  belongs_to :player
  attr_accessible :phone_id, :player_id

And to retrieve the 'leader board' I do:

@leaderboard = @team.placements.includes(:player).where(month: Date.today.beginning_of_month).order('points desc')

I want to introduce the idea of a pool, where different teams can join a pool (similar to a fantasy league). This will allow me to show the player's position in not only their team but also in a particular pool.

What would be the correct/best way to model this and to retrieve a pool's leader board?

class Team < ActiveRecord::Base
 has_many :players, dependent: :destroy
 has_many :placements, through: :players
 has_many :pools, through: :team_pools

class Placement < ActiveRecord::Base
 belongs_to :player
 attr_accessible :month, :player_id, :points, :position

class Pool < ActiveRecord::Base
 has_many :teams, through: :team_pools

class TeamPool < ActiveRecord::Base
 belongs_to :team
 belongs_to :pool

@pool_leaderboard = ?

Upvotes: 0

Views: 82

Answers (1)

Allerin
Allerin

Reputation: 1108

class Pool < ActiveRecord::Base
 has_many :teams, through: :team_pools
 has_many :placements, through => :teams

@pool_leaderboard = @pool.placements.includes(:player).where(month: Date.today.beginning_of_month).order('points desc')

Upvotes: 2

Related Questions