Using a nested object as a model property

I’m new to Ember and I’m trying to figure out if I’m missing something with using nested objects as model properties in Ember Data.

Given a JSON format like this:

{
    "name": "Some Name",
    "address": {
        "street": "123 Main Street",
        "city": "New York",
        "state": "NY"
    }
}

I can have a model like this:

name: DS.attr('string'),
address: DS.attr()

I can access the properties of the address object:

Person.get('address.street')

It seems to work fine in templates and I can used computed properties that observe the “address” property.

Am I missing something? Is this a bad pattern to follow?

You might want to try the following:

App.User = DS.Model.extend({
    name: DS.attr('string'),
    address: DS.belongsTo('address')
});

App.Address = DS.Model.extend({
    street: DS.attr('string'),
    city: DS.attr('string'),
    state: DS.attr('string'),
    person: DS.belongsTo('person')
});

Otherwise you have to “guess” the underlying data elements of the address object whereas by using the above you have explicitly defined it.

I believe that this is best practice.

Lets say we wanted to serialize a response returned by an adapter to the user model.

Will we have to create explicit non unique id field for each Address model record that we put into a User model record?

Or, since it is a belongsTo relationship, the id for the User model record should suffice?

ember-model-fragments solves this story: GitHub - adopted-ember-addons/ember-data-model-fragments: Ember Data addon to support nested JSON documents

Oh, that looks nifty. What I implemented is by use of transforms. I create an ember object and set it as a field of a parent model. But now what I see in the inspector is, if I change the nested ember object, the outer parent model object is not set to dirty :frowning: