← Back to Upcase

How do I capture human relationships in a Rails-y way?


(Marc C Gayle) #1

I have a family tree that users will be added to where they can invite other members of their family.

What I am trying to do is create a smart relationship, where if I invite my son, once I specify he is my son, then the system should automagically know that I am his father.

I figure the only way to do this is to enforce genders on all user records, which is fine.

I also have the following models:

  • FamilyTree
  • Membership
  • User

Each user has_one family_tree. Each FamilyTree has_many memberships.

So whenever a user joins a family_tree, a membership is created for them on that FamilyTree.

What I am trying to figure out though is, how do I handle the two-sided relations.
i.e. User A adds User B. I was thinking of creating a new model called Relationships that would perhaps look like this:

  • ID
  • user_one_id
  • user_two_id
  • relation

But the issue with this, is that each record doesn’t tell you exactly what’s what. i.e. it doesn’t tell you how that user1 is the father of user2, etc. So it would be dependent on the code to know that the relation is always going from the direction of user_1 -> user_2.

How do I avoid this problem altogether or figure out an alternative way to represent/think about this issue?

Thanks!


(Robert Lee-Cann) #2

I think your Relationships model might need to store two relations, one for each direction.

As an aside, it’s something graph databases are good at modelling. SQL-based databases struggle when you start querying deeply-nested relationships.

The human side of things makes things more complicated, however. I think you could easily cause offence by guessing the reverse of a relationship.


(Marc C Gayle) #3

I am thinking one for each direction, but how would that look? And then would the Relationship model not include a primary key, given that the complete answer to “What is the Relationship between Jack and Jill” would likely include two records (Jack is Jill’s husband, and Jill is Jack’s wife).

Or were you thinking of something else?