Search code examples
ember.jsmodelbelongs-to

How to get a model's name attribute?


This is really confusing me at the moment and it's probably dead simple to fix.

I have two model, related between themselves:

App.User = DS.Model.extend({
  name: DS.attr('string'),
  zip_code: DS.attr('string'),
  address_line: DS.attr('string'),
  country: DS.attr('string'),
  active: DS.attr('boolean'),
  state: DS.attr('string'),
  comments: DS.attr('string'),
  user_type: DS.belongsTo('user_type', { async: true })
});

App.UserType = DS.Model.extend({
  name: DS.attr('string'),
  users: DS.hasMany('users', { async: true })
});

I'm trying to the a User's UserType.name:

Simple enough right? Wrong!

// Doesn't work.
user.get('user_type.name');

// Also doesn't work.
user.get('user_type').get('name');

In my console, I can clearly see the object is there and related.

enter image description here


Solution

  • You will probably need to "resolve" the UserType:

    user.get('user_type').then(function(userType) {
        console.log("User type is:", userType.get('name'));
    });
    

    Note that this introduces asynchrony to your method... Depending on what you're trying to do, you'll need to accomodate for that. Normally, when bound to a Handlebars template, this resolving of related types happens automatically, so you should be able to (in a template) use {{user.user_type.name}}