“复杂”的ActiveRecord关联

时间:2013-09-15 14:10:47

标签: ruby-on-rails ruby-on-rails-3 associations rails-activerecord

在设置一些Active Record关系时遇到一些麻烦。

Users Leagues

Users有很多PrimaryLeagues Users有许多SecondaryLeagues

我希望能够编写@user.primary_leagues并获取已设置为主要的Leagues列表。和@user.secondary_leagues并获取已设置为辅助的Leagues列表。

目前我的课程是如何设置的,但不知怎的错误......

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'

有什么想法吗?

1 个答案:

答案 0 :(得分:3)

据我所知,你只想在整个事情中使用两个类(这是有道理的)。所以:

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

请记住,:class_name应该是保持目标关联的实际类。