Ember data plain array attribute

How can I model an object that has a plain array of strings? If I do the following it shows me the emails but when modifying their value they are not updated.

The server sends/receives the following data:

   "data":
	[
		{
			"attributes" : {
				"id":1,
				"name":"Jhon",
				"emails":["jhon@gmail.com","jhon@other.com"]},
				"relationships": (,..}
			}
		}

		...

Model:

export default Model.extend({
	id: attr('string'),
	name: attr('string'),
	emails: attr()
})

Template:

{{#each model.emails as |email|}}
	<input type="text" value={{email}}>
{{/each}}

First of all I’d change the transform in your model from “boolean” to nothing:

emails: attr()

You could also write a custom transform if you wanted to do anything special.

Ember Data won’t track property changes for “complex” data like that. If you want it to you’ll either need to use a relationship or look into an addon like ember-data-model-fragments

2 Likes

OK thank you, the boolean attribute was an error when writing the question. I understand that I have to use a relationship. How do I send and receive the data in the format expected by the server? I have to create a serializer?

You can totally use a simple array. Having attr() with no transform works just fine, although we use a transform partially to have self-documenting code, and to default to an empty array.

// app/transforms/array.js
import DS from 'ember-data';

export default DS.Transform.extend({
  deserialize(serialized) {
    return serialized || [];
  },

  serialize(deserialized) {
    return deserialized;
  }
});

With this, you can use:

emails: attr('array'),
3 Likes