The same object in a hasMany relationship?

Why not add the same object in a hasMany relationship?

App = Ember.Application.create();

App.Card = DS.Model.extend({});

App.CardAdapter = DS.FixtureAdapter;

App.Card.FIXTURES = [{id: '1'}];

App.Deck = DS.Model.extend({
    cards: DS.hasMany('card', {async: true})
});

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return this.store.createRecord('deck');
  }
});

App.IndexController = Ember.Controller.extend({
  actions: {
    addCardToDeck: function () {
      var _this = this;
      
      this.store.find('card', 1).then(function(card) {
        _this.get('model.cards').pushObject(card);
      });     
    }
  }
});

When I call twice addCardToDeck with the same card object (id = 1). In cards.lengths will be equal to 1

Update:

I create jsbin example

How to organize the work hasMany that, can save few equals models?

1 Like

I’m currently experiencing the same situation with a deck and cards. Any luck?

EDIT:

I pinpointed the code that’s not allowing multiples of the same record in a hasMany

ManyRelationship.prototype.addRecord = function(record, idx) {
  if (this.members.has(record)) {
    return;
  }
  this._super$addRecord(record, idx);
  this.manyArray.internalAddRecords([record], idx);
};

Seems like they are purposely not allowing this :frowning:

Yes I found this piece of code but I do not understand how to reopen.

My solution:

App = Ember.Application.create();

App.ArrayTransform = DS.Transform.extend({
    deserialize: function(serialized) {
        return (Ember.typeOf(serialized) === "array") ? serialized : [];
    },

    serialize: function(deserialized) {
        var type = Ember.typeOf(deserialized);
        if (type === 'array') {
            return deserialized;
        } else if (type === 'string') {
            return deserialized.split(',');
        } else {
            return [];
        }
    }
});

App.Card = DS.Model.extend({});

App.CardAdapter = DS.FixtureAdapter;

App.Card.FIXTURES = [{id: '1'}, {id: '2'}, {id: '3'}];

App.Deck = DS.Model.extend({
    cardIds: DS.attr('array'),
    cards: function() {
        var _this = this;
        var promise = this.store.findByIds('card', this.get('cardIds')).then(function( ) {
            var cardIds = _this.get('cardIds');
            
            return cardIds.map(function(id) {
                return _this.store.getById('card', id);
            });
        });

        return DS.PromiseArray.create({
            promise: promise
        });
    }.property('cardIds'),
});

App.IndexRoute = Ember.Route.extend({
  model: function() {
    return this.store.createRecord('deck', {cardIds: ['2', '3']});
  }
});

App.IndexController = Ember.Controller.extend({
  actions: {
    addCardToDeck: function (id) {
		var ids =  this.get('model.cardIds');

        ids.push(id);
		this.set('model.cardIds', ids);

		this.get('model').notifyPropertyChange('cardIds');  
    }
  }
});