问题:如何检索用户所在的所有小组?
我的模特:
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
我被困在哪里(我确信无论如何都有更好的方法)。
答案 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