Missing Model Relationship


#1

Hi All :slight_smile:

I am using Ember 2.x with Ember Data 2.x with the RESTApdapter.

I am struggling to make sure that my POST requests are sending the right JSON data. For example, I do something like:

 43         let posObj = this.get('store').createRecord('pos', {
 44           name: posname
 45         });
 46         posObj.save();
 48         let uObj = this.get('store').createRecord('user', {
 49           username: user,
 50         });
 52         uObj.get('poss').pushObject(posObj);
 53         uObj.save(); 

I am expecting this to save the pos object and then create a new user object with a hasMany reference to the pos object.

This does not throw an exception. However, when a request is finally made to my server at the /api/users endpoint, it only shows:

{u'user': {u'username': u'fsdaf', u'pos': [None]}}

Notice that pos shows up as None in the end result. Models look like:

User:

export default Model.extend({
  username: attr(),
  pos: hasMany('pos')
});

Pos:

export default Model.extend({
  name: attr(),
  mos: hasMany('mos'),
  users: hasMany('user')
});

Any help or suggestions would be appreciated!


#2

Possible that your posObj.save() has not resolved before you push it to poss hasMany—effectively meaning it doesn’t have an id yet and you’re adding an object with a null id to the hasmany.

Try this

let pos = this.get('store').createRecord('pos', { name: posname });
let user = this.get('store').createRecord('user', { username: user });
pos.save().then(pos => {
  user.get('poss').pushObject(pos);
  user.save();
});

Or something like that.


#3

http://emberjs.com/api/classes/RSVP.Promise.html and https://github.com/tildeio/rsvp.js/ are good places to look for more info on promises in Ember. The second link is the library that Ember uses for handling promises / asynchronous acode. :slight_smile: