在设置一些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'
有什么想法吗?
答案 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
应该是保持目标关联的实际类。