Ruby on rails 如何为用户、教练关系建模?

Ruby on rails 如何为用户、教练关系建模?,ruby-on-rails,database-design,activerecord,model,Ruby On Rails,Database Design,Activerecord,Model,在现实世界中,假设你有运动员和教练 在模型中,我有一个用户。用户是运动员。现在,用户也可以是任何其他用户的教练。您将如何以最佳方式对此进行建模 我渴望: @user.coach?=>对/错 @user.is_a_coach_of?(其他_用户)=>true/false我会有一个表,表示运动员和他们的教练之间的关系-每个运动员/教练关系的一行-其中教练和运动员ID都与用户数据相关 CoachID | AthleteID 如果任何用户都可以成为coach,那么这就是您所需要的,但是如果您想将“co

在现实世界中,假设你有运动员和教练

在模型中,我有一个用户。用户是运动员。现在,用户也可以是任何其他用户的教练。您将如何以最佳方式对此进行建模

我渴望:

@user.coach?
=>对/错


@user.is_a_coach_of?(其他_用户)
=>true/false

我会有一个表,表示运动员和他们的教练之间的关系-每个运动员/教练关系的一行-其中教练和运动员ID都与用户数据相关

CoachID | AthleteID

如果任何用户都可以成为coach,那么这就是您所需要的,但是如果您想将“coach”限制为某些用户,请在用户表中添加一个“IsCoach”属性

如果用户只能有一个coach,那么您可以在users表中将coach关联返回到users表。这方面的经典示例是employees表,其中每个员工只有一个经理(CEO除外)

类用户
有一个:coach,:class\u name=>“User”
有很多:教练,:外键=>:coach\u id,:class\u name=>“用户”
def教练?
0
如果一个用户可以有多个coach,则使用coach表,其中包含字段、user_id(用于coach)和coachee_id(用于她指导的用户)

class Coach
  belongs_to :user
  belongs_to :coachee, :class_name => "User"
end

class User
  has_many coaches, :foreign_key => :coachee_id
  has_many coach_users, :through => :coachs, :source => :user
  has_many coachees, class_name => "Coach"
  has_many coachee_users, :through => :coachees, :source => :coachee

  def coach?
    0 < coachees.count
  end

  def is_a_coach_of?(other_user)
    coachee_users.include?(other_user)
  end
end
class-Coach
属于:用户
属于:coachee,:class\u name=>“用户”
结束
类用户
有很多教练,:外国教练=>:coachee\u id
拥有多个coach用户,:至=>:coach,:源=>:用户
有很多教练,班名=>“教练”
有很多被辅导用户,:至=>:coaches,:源=>:coachee
def教练?
0
一个用户可能有许多Coach=\n在这种情况下,您会怎么做?您是否有机会用activerecord语法向我展示一下?只是想澄清一下?:)谢谢
class Coach
  belongs_to :user
  belongs_to :coachee, :class_name => "User"
end

class User
  has_many coaches, :foreign_key => :coachee_id
  has_many coach_users, :through => :coachs, :source => :user
  has_many coachees, class_name => "Coach"
  has_many coachee_users, :through => :coachees, :source => :coachee

  def coach?
    0 < coachees.count
  end

  def is_a_coach_of?(other_user)
    coachee_users.include?(other_user)
  end
end