Note that there are some explanatory texts on larger screens.

plurals
  1. POWhat's the most idiomatic way to model this relationship in Rails?
    primarykey
    data
    text
    <p>Let's say we have coaches, clients, and users.</p> <p>What's the ideal way to model this in a way that isn't inheritance? I'd like to avoid STI.</p> <p>Right now I have something like this:</p> <p>user.rb</p> <pre><code> has_many :coaches, :foreign_key =&gt; :client_id has_many :coach_users, :through =&gt; :coaches, :source =&gt; :user has_many :clients, :class_name =&gt; "Coach" has_many :client_users, :through =&gt; :clients, :source =&gt; :client def is_a_coach_of?(client) self.client_users.include?(client) end def is_a_client_of?(coach) self.coach_users.include?(coach) end </code></pre> <p>coach.rb</p> <pre><code> belongs_to :user belongs_to :client, :class_name =&gt; "User" </code></pre> <p>But this feels really clunky to deal with a User object that is supposedly a 'coach' and having to type user.coach_users to get a collection of users that are being coached by this specific user.</p> <p>It feels very non idiomatic and quite honestly, it's just plain confusing and I hate it. I want something more elegant. </p> <p>I thought of removing the join model and just having two has_many's on the user.rb model but it still feels clunky, especially the icky feeling of violating roles of objects. These are different roles but are also very similar because they're all a user. How do you separate such common logic in an elegant way, in the right idiomatic way with Rails and Ruby?</p> <p>A "user of the site" <strong>can</strong> exist without being a <code>coach</code> or a <code>client</code>.</p> <p>If the modeling requires just a relationship, then I can see it be a HABTM but what if the individual relationship requires extra logic? E.g extra logic on client or coach? Would you just mixin a class that defines logic in the User model? Or would you create separate AR models for the relationship and if so, how?</p>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload