在现实世界中,假设您有运动员和教练。
在模型中我有一个用户。用户是运动员。现在一个用户也可以是任何其他用户的教练。您将如何以最佳方式对此进行建模?
我渴望:
@user.coach?
=> 真/假
@user.is_a_coach_of?(other_user)
=> 真/假
在现实世界中,假设您有运动员和教练。
在模型中我有一个用户。用户是运动员。现在一个用户也可以是任何其他用户的教练。您将如何以最佳方式对此进行建模?
我渴望:
@user.coach?
=> 真/假
@user.is_a_coach_of?(other_user)
=> 真/假
如果一个用户只能有一个教练,那么您可以将用户表上的教练关联回用户表。典型的例子是员工表,其中每个员工只有一位经理(CEO 除外)。
class User
has_one :coach, :class_name => "User"
has_many :coachees, :foreign_key => :coach_id, :class_name => "User"
def coach?
0 < coachees.count
end
def is_a_coach_of?(other_user)
coachees.include?(other_user)
end
end
如果一个用户可以有很多教练,那么使用一个教练表,其中包含字段 user_id(针对教练)和针对她教练的用户的 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
我会有一个代表运动员和他们的教练之间关系的表格——每个运动员/教练关系的一行——教练和运动员 ID 都与用户数据相关。
CoachID | AthleteID
如果任何用户都可以成为教练,那么这就是您所需要的,但如果您想将“教练”限制为某些用户,请将“IsCoach”属性添加到用户表