Search code examples
ruby-on-railsdatabase-designactiverecordmodel

How to model a user, coach relationship?


In my model I have a user. The user is the athlete. A user may also be a coach to any other user. How to model this?

I have:

@user.coach? => true/false

@user.is_a_coach_of?(other_user) => true/false


Solution

  • If a user can only have one coach, then you can have a coach association on the users table back to the users table. The classic example of this is an employees table, where every employee has exactly one manager (except the 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
    

    If a user could have many coaches, then use a coaches table, with fields, user_id (for the coach) and coachee_id for the user that she coaches.

    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