slindsey3000
slindsey3000

Reputation: 4281

"Complex" ActiveRecord association

having some trouble setting up some Active Record relationships.

Users Leagues

Users have many PrimaryLeagues Users have many SecondaryLeagues

I would like to be able to write @user.primary_leagues and get a list of Leagues that have been set as primary. and @user.secondary_leagues and get a list of Leagues that have been set as secondary.

Currently here is how my classes are set up, but it is wrong somehow....

class User < ActiveRecord::Base

has_many :primary_leagues, class_name: 'PrimaryLeague', foreign_key: 'league_id'

has_many :secondary_leagues, class_name: 'SecondaryLeague', foreign_key: 'league_id'

...

class PrimaryLeague < ActiveRecord::Base

belongs_to :user
belongs_to :league

...

class League < ActiveRecord::Base

has_many :primary_users, class_name: 'PrimaryLeague', foreign_key: 'user_id'
has_many :secondary_users, class_name: 'SecondaryLeague', foreign_key: 'user_id'

Any ideas?

Upvotes: 0

Views: 125

Answers (1)

Marcelo De Polli
Marcelo De Polli

Reputation: 29291

As I understand, you want to use only two classes for the whole thing (and that makes sense). So:

class User < ActiveRecord::Base
  has_many        :primary_league_ownerships
  has_many        :primary_leagues,
                  :through => :primary_league_ownerships,
                  :source => :league
  has_many        :secondary_league_ownerships
  has_many        :secondary_leagues,
                  :through => :secondary_league_ownerships,
                  :source => :league
end

class PrimaryLeagueOwnership < ActiveRecord::Base
  belongs_to      :user
  belongs_to      :league
end

class SecondaryLeagueOwnership < ActiveRecord::Base
  belongs_to      :user
  belongs_to      :league
end

class League < ActiveRecord::Base
  has_many        :primary_league_ownerships
  has_many        :primary_users,
                  :through => :primary_league_ownerships,
                  :source => :user
  has_many        :secondary_league_ownerships
  has_many        :secondary_users,
                  :through => :secondary_league_ownerships,
                  :source => :user
end

Keep in mind that :class_name is supposed to be the actual class that will hold the target association.

Upvotes: 3

Related Questions