检索用户所在的所有团队

时间:2014-08-12 01:41:02

标签: 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 :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
  • 用户可以拥有多个团队(成为'所有者',但不一定是'在'那些团队'上)。
  • 用户已开启 许多球队的“大师”名单。

尝试: 我试图抓住数据库中的所有主要名单:

# User class:

def teams_on
  # All the rosters the user is on.
  r = Roster.includes(:rosterplayers).where(rosterplayers: { user_id: self.id })

  # Get only master rosters.
  m = r.where(master: true)
end

我被困在哪里(我确信无论如何都有更好的方法)。

1 个答案:

答案 0 :(得分:0)

所以我在搜索了一下之后找到了答案:

Retrieve all posts where the given user has commented, Ruby on Rails

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

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

def teams_on
  self.team_enrollments
end