I was building a Rails app which required a Contacts model to be able to relate to many other contacts where the relationship was reciprocal.
The Database
Because contacts can have relationships with many other contacts I knew I needed another table to track this and knew I needed a has_many :through association.
Rails has another association called has_and_belongs_to_many which also could have worked but it’s not as easy to work with as it doesn’t have any intervening model and doesn’t offer flexibility like adding extra columns.
Creating the migration.
The associations
Next I needed to setup the associations.
Great I could now create the relationships but the problem was the relationship would only be viewable from the contact who created the relationship and not the other way around.
So on the contact model I created an association for the inverse of the relationship.
But then to get both sides of a relationship I had to go through 2 associations or do lookups on both columns:
While this was worked it just didn’t seem efficient or elegant.
A better way
So I decided to refactor this inverse association and instead when a relationship is created I would use callback to create (and destroy) the inverse relationship in the database.
While this creates more database records in the relationships table the lookup queries are so much better now.