Toran Billups
Toran Billups

Reputation: 27399

How to submit a form with related model data in ember-data 1.0?

I'm creating a record from both form data and another promise (for the related record).

Here is the basic JSON I'm centered around

//appointment
{
  "id": 6,
  "details": "test",
  "customer": 1
}

//customer
{
  "id": 1,
  "name": "Sle eep",
  "appointments": [6]
}

My ember-data models look like this

App.Appointment = DS.Model.extend({
  details: attr('string'),
  customer: belongsTo('customer', { async: true})
});

App.Customer = DS.Model.extend({
  name: attr('string'),
  appointments: hasMany()
});

When I create an appointment it currently looks something like this

this.store.find('customer', 1).then(function(customer) {
  var appointment = {
    details: 'foo',
    customer: customer.get('id')
  }
  this.store.createRecord('appointment', appointment).save();
});

The problem with the above is that my serializer doesn't do well when the form data is a promise. Is this how I should be creating records? If not, what should this create look like?

Thank you in advance

Update

After a little more looking around, it seems the async: true on belongsTo might be the issue. Just before the "createRecord" I can see the following

Object {details: "asd", customer: 1}

But when I jump into the "createRecord" method of ember-data (in the RESTAdapter) I notice that now customer is represented as a promise again (not the integer value or string value I saw just before that method was invoked)

Upvotes: 2

Views: 159

Answers (1)

Kingpin2k
Kingpin2k

Reputation: 47367

Why don't you wait for the find to be resolved before creating the record and sending?

var self = this,
    promise = this.store.find('customer', 1); //just to show it's a promise

promise.then(function(customer){

  var appointment = {
    details: 'foo',
    customer: customer
  }
  self.store.createRecord('appointment', appointment).save();
},{
  alert("uh oh end of the world, couldn't find customer");
});

Async isn't extremely well documented and seems to have some willy-nilly side-effects (It is all still in beta, so no major judgement from me yet). That being said, your appointments hasMany isn't defined, here's a playground for this.

http://emberjs.jsbin.com/OlaRagux/5/edit

Upvotes: 2

Related Questions