F
F
fsamorodov2015-12-15 18:24:17
Ember.js
fsamorodov, 2015-12-15 18:24:17

How to push an object into an array in Emberjs without using hasMany?

Hello!
I have a model

var attr = DS.attr,
    hasMany = DS.hasMany;

export default DS.Model.extend({
  date: attr('string'),
  lists: hasMany('other-model')
});

The task is to store the lists string in a regular array, and not through the hasMany bundle.
My controller:
addList: function() {
            var This = this;
            var report = this.get('model');
            report.get('lists').pushObject({
                    summ: This.get('summ'),
                    comment: This.get('comment'),
                    unit: This.get('unit')
                });

                report.save();
                This.set('summ', '');
                This.set('comment', '');
                This.set('err', '');

But this option does not work :(
In the model I tried to change hasMany to string and ''
Another question is how to delete one of the lists later?

Answer the question

In order to leave comments, you need to log in

2 answer(s)
O
Olga Zakharskaya, 2015-12-15
@OZakharskaya

Maybe this article will help? look...

A
Andrey Sherstobitov, 2016-01-30
@Astralet

So, by default, it seems that the Ember-Data serializer should, when saving the hasMany relationship, just pass an array of id models.
Or rewrite DS.RESTSerializer (or JSONSerializer - depending on how you load the data) to suit your requirements. It has a serializeHasMany method. There already logic of preservation can be described any.
Here is a piece from my code.

serializeHasMany: function(snapshot, json, relationship) {
    var key = relationship.key;
    var isPoly = relationship.options.polymorphic;
    if (key === 'attaches') {
    	var hasMany = snapshot.hasMany(key);
    	var result = [];
    	hasMany.forEach(function(item) {
    		result.push({id: item.id, type: item.modelName}); //вот здесь я формирую структуру для полиморфного отношения, для отправки на сервер
    	});
    	json[key] = result;
      return json;
    } else {
      this._super.apply(this, arguments);
    }
  }

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question