Ruby on rails 检索用户所在的所有团队

Ruby on rails 检索用户所在的所有团队,ruby-on-rails,Ruby On Rails,问题:如何检索用户所在的所有团队 我的模型: class User < ActiveRecord::Base has_many :teams, :uniq => true has_many :rosterplayers has_many :rosters, -> { uniq } , :through => :rosterplayers end class Roster < ActiveRecord::Base has_many :rosterp

问题:如何检索用户所在的所有团队

我的模型:

class User < ActiveRecord::Base
  has_many :teams, :uniq => true
  has_many :rosterplayers
  has_many :rosters, -> { uniq } ,  :through => :rosterplayers
end

class Roster < ActiveRecord::Base
  has_many :rosterplayers
  has_many :users, -> { uniq }, through: :rosterplayers
end

class Rosterplayer < ActiveRecord::Base
  belongs_to :roster
  belongs_to :user
  validates :user_id, :uniqueness => { :scope => :roster_id }
end

class Team < ActiveRecord::Base
  # user is the creator of the team
  belongs_to :user 

  # Roster.roster_master(team) is the team's master (full) roster
  has_many :rosters
end

我被困住了,我确信还有更好的方法。

因此,我在搜索了更多信息后找到了答案:

我所要做的就是将其添加到用户模型中:

has_many :team_enrollments, :through => :rosters, :source => :team

def teams_on
  self.team_enrollments
end
has_many :team_enrollments, :through => :rosters, :source => :team

def teams_on
  self.team_enrollments
end