2

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
            )

    )
Mike
  • 12,359
  • 17
  • 65
  • 86

1 Answers1

4

Update Feb-26-2014

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')
});
Teddy Zeenny
  • 3,971
  • 1
  • 17
  • 20
  • Thanks Teddy Zeenny, which option do you think is the better approach? I like the idea of creating the array type, but if it is not already part of Ember I am sure there is a reason, so kinda leaning toward the first way... – Mike Mar 13 '13 at 17:59
  • I'd say it depends on your use case, if the `conditionValues` is actually a standalone model that you want to perform CRUD operations on, then the first approach is better. If it's just a read-only array generated on the fly before sending the JSON, then it's safe to go with option 2. – Teddy Zeenny Mar 13 '13 at 18:12
  • That makes sense, but why is this not already implemented in Ember? Maybe to prevent confusion – Mike Mar 13 '13 at 18:49
  • Because most use cases are the first option. The second scenario is very rare. – Teddy Zeenny Mar 13 '13 at 19:19
  • for the lurkers, the current transform docs state ex. 2 should be: `App.ArrayTransform = DS.Transform.extend({ ... })` – arminrosu Oct 27 '13 at 22:23