0

在设置一些 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'

有任何想法吗?

4

1 回答 1

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应该是持有目标关联的实际类。

于 2013-09-15T14:29:37.163 回答