Reputation: 22234
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.
Upvotes: 0
Views: 183
Reputation: 612
Because you've set the relationship as {async: true}
, Ember presumes that the relationship is asynchronous, i.e. it needs to load the UserType
model separately. So, at least the first time it's called, user.get('user_type')
actually returns a promise which, at the point at which the chained method is called, is not guaranteed to have loaded content.
Even if it's already in the store, (if memory serves) Ember is not going to attempt to set it until the next run loop. Calling .get('name')
on that promise immediately will thus give you null
.
The user.get('user_type.name')
syntax will just resolve internally to the same thing as user.get('user_type').get('name')
so that result will be no different.
Steve H.'s response should work. Alternatively, if you're working with a server (not fixtures) and the server response is such that the userType
is sideloaded with the user – or if you are in a position to change the response – you should be able to remove the {async: true}
conditions, and both of the expressions in your question should work as expected.
Upvotes: 1
Reputation: 6947
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}}
Upvotes: 1