Question

So here's my question, I'm not sure how to properly create record of a model that has a belongs to. I have 2 models.

App.Group = DS.Model.extend({
  peeps: hasMany('people'),
});

App.People = DS.Model.extend({
  group: belongsTo('group')
});     

So in the app I can do it 2 ways

 var group = someGroup; // this is a reference to an actual group record
 var record = store.createRecord('people', { group: group});

And then the 'belongsTo' properly works throughout the app, but when I try and save the json sent back to the server is

 { 'people' : { 'group' : { //group values except id, since ember data 
      doesn't try and serialize the belongsTo record } } }

So then I don't have anyway of knowing which record the People record is supposed to be saved to.

OR I can create the record with the id

 var group = someGroup; // this is a reference to an actual group record
 var record = store.createRecord('people', { group: group.get('id')});

but then I can't use the record's belongTo properly anymore. It doesn't link up to anything, it's just a plain ol' id. Yet when I save I get { 'people' : {'group' : id } }.

Until I figure it out, I've added some terrible hackery

//weird hackary for a sec while I figure out ember data.
record.set('group', group.get('id'));
record.save().then(function(){
   record.set('group', group);
});

Any suggestions/ideas?

(as a side note, I might be seeing if I set the id, then save, it might reload based on the results from the server and then hookup the belongsTo, but that's assuming I save right after I create, which I don't want to have to assume)

Was it helpful?

Solution

Turns out I had the property defined twice in the model, one as a belongsTo and one as an attr.

App.People = DS.Model.extend({
  group: DS.belongsTo('group')
  group: DS.attr() <---- whoops
});   

How it should be done though (for those who hit this page)

App.Group = DS.Model.extend({
  peeps: DS.hasMany('people'),
});

App.People = DS.Model.extend({
  group: DS.belongsTo('group')
});   
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top