【问题标题】:Retrieve all Teams that User is on检索用户所在的所有团队
【发布时间】:2014-08-12 11:00:29
【问题描述】:

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

我的模特:

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

我不知道从哪里开始(我相信无论如何都有更好的方法)。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

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

    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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-23
      • 2019-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多