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

私が理解しているように、全体で 2 つのクラスのみを使用する必要があります (これは理にかなっています)。そう:

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 に答える