【发布时间】: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