3

Imagine we have two entities, stored in a relational database as:

person(id, name)

friendship(id, personAID, personBID, strength)

Here we can see that two people can be friends and a "strength" (some numerical value) will be given to that friendship. If persons 1 and 2 are friends, then we have the following entry in the friendship table:

xyz | 1 | 2 | 50

note that the following corresponding entry does not exist:

abc | 2 | 1 | 50

Only one entry is created per "friendship".

What I struggle with is how to model this in the ember app. A "person" can have many friendships, and a "friendship" relates exactly 2 people.

// models/person.js
DS.Model.extend({
    name: DS.attr('string'),
    friendships: DS.hasMany('friendship', {inverse: 'friends'})
});

The friendship objects are serialized as an array of

{
    id: 'abc',
    friends: ['1', '2'],
    score: '50'
}

so:

// models/friendship.js
DS.Model.extend({
    friends: DS.hasMany('person', {inverse: friendships}),
    personA: Ember.computed(friends, function() {
        return this.get('friends').objectAt('0');
    }),
    personB: Ember.computed(friends, function() {
        return this.get('friends').objectAt('1');
    }),
    getFriend: function(id) {
        if (id === this.get('personA.id')) {
            return this.get('personB');
        }
        if (id === this.get('personB.id')) {
            return this.get('personA');
        }
        return null;
    },
    score: DS.attr('number')
});

The implementation of the friendship model feels hacky for lots of reasons. First of all, a friendship does not "have many" friends. It has exactly two. However, if I change the implementation to:

DS.Model.extend({
    personA: DS.belongsTo('person'),
    personB: DS.belongsTo('person'),
    ...
});

then I'm not sure how to model the "hasMany" relationship of person => friendship. What would the 'inverse' field be set to, for instance?

The "score" field is complicating things. If that didn't exist then this would be a reflexive relation within the "person" model, but the relation has additional data and must be able to be represented as its own entity.

Also, given the situation where I want to list all of the friends of a given person, along with the strength of that friendship, the "getFriend()" function is required. This function smells a bit to me and I can't quite put my finger on why.

So my question is, what do you see as an effective way to model two-way symmetric relationships that contain additional data such as the "score" field? I can't change anything about how the data is stored in the DB, but I do have control over everything else, so I can transform the data into any structure on the way out of the DB and into the Ember client.

Ember and Ember-data 2.x

3
  • FWIW, I've solved this problem before by creating a separate model for the relationship. That comes with its own set of drawbacks, but it worked well enough.
    – GJK
    Dec 10, 2015 at 0:44
  • 1
    I've gotten so far as to create a (Rails) API that returns the two-way relationships. At this point, it only has a /people endpoint that returns the relationship links but it can be extended and the relationships work at the ActiveRecord level. Jan 4, 2016 at 9:03
  • 1
    Oops, I forgot the actual link to the API's repository: github.com/balinterdi/two-way-symmetric-relationships-api Jan 4, 2016 at 10:20

1 Answer 1

4

So it took me a year but I finally came back to this problem and I think I have a fairly good solution for it. I actually wrote two blog posts detailing the solution (part 1 and part 2), but let me try to summarize it here.

The solution has both a front-end and a back-end component to it.

I defined the models (in Rails, but it could be anything really) as follows:

# app/models/friendship.rb
class Friendship < ActiveRecord::Base
  belongs_to :friender, class_name: Person
  belongs_to :friended, class_name: Person
end

# app/models/person.rb
class Person < ActiveRecord::Base
  def friendships
    Friendship.where("friender_id = ? OR friended_id = ?", id, id);
  end
end

I used a JSON API compliant backend and a gem called jsonapi-resources to help me implement the server response. Whatever your implementation, the important piece is to have an endpoint for each person that returns the friendships for that person (e.g /people/1/friendships).

That endpoint should return the relationship links where data could be fetched to see who the people are on both sides of the relationships:

{
  "data": [
    {
      "id": "1",
      "type": "friendships",
      (...)
      "attributes": {
        "strength": 3
      },
      "relationships": {
        "friender": {
          "links": {
            "self": "http://localhost:4200/friendships/1/relationships/friender",
            "related": "http://localhost:4200/friendships/1/friender"
          },
          "data": {
            "type": "people",
            "id": "1"
          }
        },
        "friended": {
          "links": {
            "self": "http://localhost:4200/friendships/1/relationships/friended",
            "related": "http://localhost:4200/friendships/1/friended"
          },
          "data": {
            "type": "people",
            "id": "4"
          }
        }
      }
    },
    {
      "id": "2",
      "type": "friendships",
      (...)
    }
  ]
}

The models on the Ember side looks as follows:

// app/models/person.js
import DS from 'ember-data';
import Model from 'ember-data/model';

export default Model.extend({
  name: DS.attr(),
  friendships: DS.hasMany(),
  frienderFriendships: DS.hasMany('friendship', { inverse: 'friender' }),
  friendedFriendships: DS.hasMany('friendship', { inverse: 'friended' }),
});

// app/models/friendship.js
import DS from 'ember-data';
import Model from 'ember-data/model';

export default Model.extend({
  strength: DS.attr('number'),
  friender: DS.belongsTo('person', { inverse: 'frienderFriendships' }),
  friended: DS.belongsTo('person', { inverse: 'friendedFriendships' }),
});

In the route I'm fetching the person and just display their friendships in the simplest way:

<h2>Friends of {{model.name}}</h2>
<ul>
  {{#each model.friendships as |friendship|}}
    <li>{{friendship.friender.name}} - {{friendship.friended.name}} - {{friendship.strength}}</li>
  {{/each}}
</ul>

That works, but sends out lots of xhr requests to the backend, one for each end (friender and friended) of the relationship.

You can cut down on the number of these requests by using resource linkage in the response of the friendships endpoint. If you don't use JSON API, there are surely ways to indicate which record is on the ends of a relationship (friendship.friender or friendship.friended) so that no further ajax requests need to be made to fetch them.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.