Search code examples
javascriptember.jsember-data

Setting a new relation in EmberJS without original model


So I have a model created/loaded normally:

        let contact = self.get('store').createRecord('contact');

I then get the address, which is a BelongsTo relation on the model:

        let address = contact.get('address');

the returned address variable is a Proxy object, which the promise resolves as either the related model or null.

The question is how can I create a new address model and assign it to the original contact object, but with only the address proxy object?


Solution

  • If you want to create a new address record (and not model) and assigning it to your newly created contact, you can do the following:

    const store = this.get('store');
    const contact = store.createRecord(
        'contact',
        {
            name: 'Jack',
            address: store.createRecord('address')
        }
    );
    

    or if you already have an address proxy and you want to create a new one only if it results to null:

    const store = this.get('store');
    const contact = store.createRecord('contact', { name: 'Jack' });
    my_address_proxy.then(address => {
        contact.set('address', address || store.createRecord('address'));
    });