Reputation: 12819
What is the proper way to use an array in an Ember data model? Tom Dale points out that ember has "embedded hasOne relationships" in this comment, but I am not able to find any documentation or examples of this in action.
For example I have a Category
data model like so that has a property called conditionValues
App.Category = DS.Model.extend({
name: DS.attr('string'),
conditionValues: //this is an array
});
I would like to populate this property with an array returned from my server like the one below. Each category has many condition values
. How might one go about doing this?
[condition_values] => Array
(
[0] => Array
(
[DisplayName] => Brand New
)
[1] => Array
(
[DisplayName] => Like New
)
[2] => Array
(
[DisplayName] => Very Good
)
[3] => Array
(
[DisplayName] => Good
)
[4] => Array
(
[DisplayName] => Acceptable
)
)
Upvotes: 2
Views: 2209
Reputation: 3971
The code in this answer no longer works since Ember Data 1.0 beta and above.
You can handle that in two ways:
First way is to define a model called App.ConditionValues
and then define a relationship:
App.Category = DS.Model.extend({
//.. your attributes
conditionValues: DS.hasMany('App.ConditionValues')
});
Second way it to create your own custom transform.
DS.RESTAdapter.registerTransform('array', {
serialize: function(value) {
if (Em.typeOf(value) === 'array') {
return value;
} else {
return [];
}
},
deserialize: function(value) {
return value;
}
});
and then in your model:
App.Category = DS.Model.extend({
//.. your attributes
conditionValues: DS.attr('array')
});
Upvotes: 4