1
votes

I'm trying to implement a friending system in Ember, which is a many-to-many relationship. My models are:

App.User = DS.Model.extend
  name: DS.attr('string')
  friendships: DS.hasMany('friendship', { inverse: 'user' })

App.Friendship = DS.Model.extend
  user: DS.belongsTo('user')
  friend: DS.belongsTo('user')

In my User controller, I have an addFriend action that looks roughly like this (I have currentUser defined from elsewhere):

App.UserController = Ember.ObjectController.extend
  actions:
    addFriend: ->
      friendship = @get('store').createRecord('friendship', 
        user: @get('currentUser')
        friend: @get('model')
      )
      @get('currentUser.friendships').pushObject(friendship)

From debug statements, it seems like the friendship record is being pushed into the friendships array of BOTH currentUser and the user represented by model. I don't want this to happen, because for a bidirectional friending system, the model.friendship array should contain the inverse of friendship i.e. with user and friend swapped. Of course it would be nice if Ember had a way to do this automatically, but I'm perfectly happy to do it manually as well.

For now, why is the pushObject method pushing the same friendship record into both user records? I guess it might have something to do with the way inverses are defined in the models. I tried changing to inverse: null but that did not solve the problem. What is happening under the hood with ember-data that is causing this behavior? Or is there a bug in my code somewhere that I have not seen? Any way to get rid of this behavior would be much appreciated!

1

1 Answers

1
votes

Solved! It turns out I needed

App.Friendship = DS.Model.extend
  user: DS.belongsTo('user')
  friend: DS.belongsTo('user', { inverse: null })

I was intuitively right that the answer had something to do with inverses, but I didn't put the inverse: null in the correct place at first!