Ember model access to belongsTo property return null

410 Views Asked by At

I have a model Person with this property : address_fk: DS.belongsTo('address') refering to an Address model.

In the adress model, there are several properties such as zip_code , building ...

My goal is to create a computed property in Person to display the full address by accessing this.get('address_fk.zip_code') but it returns me undefined

I'm surely missing something here but I really don't know what.

Update : Problem solved, here is how :

adresse: computed('adresse_fk', function() {
return DS.PromiseObject.create({
  promise: this.get('adresse_fk').then((adresse) => {
    return adresse.get('escalier_etage_appartement') + ' ' + adresse.get('batiment') + ' ' + adresse.get('numero_nom_voie') + ' ' + adresse.get('code_postal') + ' ' + adresse.get('commune_fk.nom')
  })
});

}),

2

There are 2 best solutions below

1
vikasnautiyal On BEST ANSWER

you are defining the computed property on the Person model. The computed property may return a PromiseObject for the address. You could try these two things -

1 Check for the presence of adresse_fk

// Person model
adresse: Ember.computed('adresse_fk', function() {
if this.get('adresse_fk'){
  return this.get('adresse_fk.escalier_etage_appartement') + ' ' 
   + this.get('adresse_fk.batiment') + ' ' + 
   this.get('adresse_fk.numero_nom_voie')
}

2 Use then to resolve promises

// Person model
adresse: Ember.computed('adresse_fk', function() {
this.get('adresse_fk').then( function(address){
  return address.get('escalier_etage_appartement') + ' ' 
   + address.get('batiment') + ' ' + 
   address.get('numero_nom_voie')
 }
}

I have not tested them but they should work.

0
El Poisen On
//Address
export default DS.Model.extend({
    point_de_consommation_fk: DS.hasMany('pointdeconsommation'),
    code_postal: DS.attr('string'),
    escalier_etage_appartement: DS.attr('string'),
    batiment: DS.attr('string'),
    numero_nom_voie: DS.attr('string'),
    commune_fk: DS.belongsTo('commune'),
    personne_set: DS.hasMany('personne')
})

// Person model
export default DS.Model.extend({
     categorie_code: DS.attr('personne-categorie-code'),
     email: DS.attr('string'),
     adresse_fk: DS.belongsTo('address'),
     telephone1: DS.attr('string'),
     telephone2: DS.attr('string', {defaultValue: ''}),
     adresse: computed('adresse_fk', function() {
       return this.get('adresse_fk.escalier_etage_appartement') + ' ' 
       + this.get('adresse_fk.batiment') + ' ' + 
       this.get('adresse_fk.numero_nom_voie')
     }),
})

I also forgot to tell that sometimes my undefined value is showing up. Maybe I need to wait on my template before calling the property?