Help me understand relationships in ember-data


#1

Suppose I want to create a Card, and I’ve defined a Discounts relationship that a card has many discounts

Now I create a Card record with a pre-filled Discount in route:

let newCard = this.store.createRecord('card', {
  name: 'A new Card',
  // ... other attributes
  discounts: Ember.A()
})

newCard.get('discounts').addObject(
  this.store.createRecord('discount', {
    name: 'A new Discount',
   // ... other attributes
  })
)

Now, in the template & controller, I can manipulate this card and its discounts as expected.

Later, I try to save this card:

this.controller.get('model.card').save()

The request is sent, but then I found the request’s payload is not complete, discounts array is not included in it. But if you use Ember Inspector, you still can see those data with the right relationship with new card.

I try to set a breakpoint before request has been sent, discounts array is not included in the request snapshot, I don’t understand why relationships are excluded from the request payload, how am I suppose to contain these data in the payload?


#2

I was tracking down the source code and found at here:

This can explain why discounts has not been serialized and push into the request payload, but I just don’t understand the reason, why a "manyToOne" relationship will not be include? it this is the intentional design goal, then how to persist a new record which has this kind of relationship?


#3

Yes… it isn’t included… by default you always want to save the relationship on the many side. take a look in this issue https://github.com/emberjs/data/issues/3892