Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ember.js data associations not saving

Let's say I have 2 models:

App.Address = DS.Model.extend({
   street: DS.attr('string'),
   person: DS.belongsTo('App.Person')
})

App.Person = DS.Model.extend({
  name: DS.attr('string'),
  addresses: DS.hasMany('App.Address')
})

Now I create a person

App.person = App.Person.createRecord({name: 'Bill'});
App.store.commit();

If I try to add an address to the person like this

address = App.Address.createRecord({street: '123 Fake Street'});
App.person.get('addresses').pushObject(address);

and commit the transaction

App.store.commit();

The new address will be saved however the person object will not be recognized as changed; even though the list of ids has gone from

{
  ...
  "addresses": []
}

to

{
  ...
  "addresses": [3]
}

Is there a way to let ember-data know that my person object has been changed and it needs to be saved?

Edit: Here is a jsfiddle illustrating the problem.

like image 969
CamShaft Avatar asked Jul 14 '12 01:07

CamShaft


2 Answers

As of now (ember-data revision 4) there is no way to do this. The object is only persisted on the belongsTo side since it has the foreign key, so if you set the value in the belongs to side of the relation it should persist. The next version of ember data should address this issue.

like image 109
Gaurav Shetty Avatar answered Oct 02 '22 07:10

Gaurav Shetty


The work around I've found for this would be to just manually add the id like:

App.Address = DS.Model.extend({
   street: DS.attr('string'),
   personID: DS.attr('string'),
   person: DS.belongsTo('App.Person')
})

then when you send your data, set the personId field and it'll mimic what the person field seems like it should send.

like image 27
hobberwickey Avatar answered Oct 02 '22 07:10

hobberwickey