DS.Model

The model class that all Ember Data records descend from. This is the public API of Ember Data models. If you are using Ember Data in your application, this is the class you should use. If you are working on Ember Data internals, you most likely want to be dealing with InternalModel

Show:

This property holds the DS.AdapterError object with which last adapter operation was rejected.

A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are the meta object for the property.

Example

1
2
3
4
5
6
7
import DS from 'ember-data';

export default DS.Model.extend({
   firstName: DS.attr('string'),
   lastName: DS.attr('string'),
   birthday: DS.attr('date')
 });
1
2
3
4
5
6
7
8
9
10
11
12
13
import Ember from 'ember';
import Person from 'app/models/person';

let attributes = Ember.get(Person, 'attributes')

attributes.forEach(function(meta, name) {
   console.log(name, meta);
 });

// prints:
// firstName {type: "string", isAttribute: true, options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", isAttribute: true, options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", isAttribute: true, options: Object, parentType: function, name: "birthday"}

If the record is in the dirty state this property will report what kind of change has caused it to move into the dirty state. Possible values are:

  • created The record has been created by the client and not yet saved to the adapter.
  • updated The record has been updated by the client and not yet saved to the adapter.
  • deleted The record has been deleted by the client and not yet saved to the adapter.

Example

1
2
let record = store.createRecord('model');
record.get('dirtyType'); // 'created'

When the record is in the invalid state this object will contain any errors returned by the adapter. When present the errors hash contains keys corresponding to the invalid property names and values which are arrays of Javascript objects with two keys:

  • message A string containing the error message from the backend
  • attribute The name of the property associated with this error message
1
2
3
4
5
6
record.get('errors.length'); // 0
record.set('foo', 'invalid value');
record.save().catch(function() {
  record.get('errors').get('foo');
  // [{message: 'foo should be a number.', attribute: 'foo'}]
});

The errors property us useful for displaying error messages to the user.

1
2
3
4
5
6
7
8
9
10
11
12
<label>Username: {{input value=username}} </label>
{{#each model.errors.username as |error|}}
  <div class="error">
    {{error.message}}
  </div>
{{/each}}
<label>Email: {{input value=email}} </label>
{{#each model.errors.email as |error|}}
  <div class="error">
    {{error.message}}
  </div>
{{/each}}

You can also access the special messages property on the error object to get an array of all the error strings.

1
2
3
4
5
{{#each model.errors.messages as |message|}}
  <div class="error">
    {{message}}
  </div>
{{/each}}

A map whose keys are the fields of the model and whose values are strings describing the kind of the field. A model's fields are the union of all of its attributes and relationships.

For example:

1
2
3
4
5
6
7
8
9
10
import DS from 'ember-data';

export default DS.Model.extend({
   users: DS.hasMany('user'),
   owner: DS.belongsTo('user'),

   posts: DS.hasMany('post'),

   title: DS.attr('string')
 });
1
2
3
4
5
6
7
8
9
10
11
12
13
import Ember from 'ember';
import Blog from 'app/models/blog';

let fields = Ember.get(Blog, 'fields');
fields.forEach(function(kind, field) {
   console.log(field, kind);
 });

// prints:
// users, hasMany
// owner, belongsTo
// posts, hasMany
// title, attribute

If this property is true the record is in the dirty state. The record has local changes that have not yet been saved by the adapter. This includes records that have been created (but not yet saved) or deleted.

Example

1
2
3
4
5
6
7
8
let record = store.createRecord('model');
record.get('hasDirtyAttributes'); // true

store.findRecord('model', 1).then(function(model) {
  model.get('hasDirtyAttributes'); // false
  model.set('foo', 'some value');
  model.get('hasDirtyAttributes'); // true
});

All ember models have an id property. This is an identifier managed by an external source. These are always coerced to be strings before being used internally. Note when declaring the attributes for a model it is an error to declare an id attribute.

1
2
3
4
5
6
let record = store.createRecord('model');
record.get('id'); // null

store.findRecord('model', 1).then(function(model) {
  model.get('id'); // '1'
});

If this property is true the record is in the deleted state and has been marked for deletion. When isDeleted is true and hasDirtyAttributes is true, the record is deleted locally but the deletion was not yet persisted. When isSaving is true, the change is in-flight. When both hasDirtyAttributes and isSaving are false, the change has persisted.

Example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
let record = store.createRecord('model');
record.get('isDeleted');    // false
record.deleteRecord();

// Locally deleted
record.get('isDeleted');           // true
record.get('hasDirtyAttributes');  // true
record.get('isSaving');            // false

// Persisting the deletion
let promise = record.save();
record.get('isDeleted');    // true
record.get('isSaving');     // true

// Deletion Persisted
promise.then(function() {
  record.get('isDeleted');          // true
  record.get('isSaving');           // false
  record.get('hasDirtyAttributes'); // false
});

If this property is true the record is in the empty state. Empty is the first state all records enter after they have been created. Most records created by the store will quickly transition to the loading state if data needs to be fetched from the server or the created state if the record is created on the client. A record can also enter the empty state if the adapter is unable to locate the record.

If true the adapter reported that it was unable to save local changes to the backend for any reason other than a server-side validation error.

Example

1
2
3
4
5
record.get('isError'); // false
record.set('foo', 'valid value');
record.save().then(null, function() {
  record.get('isError'); // true
});

If this property is true the record is in the loaded state. A record enters this state when its data is populated. Most of a record's lifecycle is spent inside substates of the loaded state.

Example

1
2
3
4
5
6
let record = store.createRecord('model');
record.get('isLoaded'); // true

store.findRecord('model', 1).then(function(model) {
  model.get('isLoaded'); // true
});

If this property is true the record is in the loading state. A record enters this state when the store asks the adapter for its data. It remains in this state until the adapter provides the requested data.

If this property is true the record is in the new state. A record will be in the new state when it has been created on the client and the adapter has not yet report that it was successfully saved.

Example

1
2
3
4
5
6
let record = store.createRecord('model');
record.get('isNew'); // true

record.save().then(function(model) {
  model.get('isNew'); // false
});

If true the store is attempting to reload the record from the adapter.

Example

1
2
3
record.get('isReloading'); // false
record.reload();
record.get('isReloading'); // true

If this property is true the record is in the saving state. A record enters the saving state when save is called, but the adapter has not yet acknowledged that the changes have been persisted to the backend.

Example

1
2
3
4
5
6
7
let record = store.createRecord('model');
record.get('isSaving'); // false
let promise = record.save();
record.get('isSaving'); // true
promise.then(function() {
  record.get('isSaving'); // false
});

If this property is true the record is in the valid state.

A record will be in the valid state when the adapter did not report any server-side validation failures.

Represents the model's class name as a string. This can be used to look up the model's class name through DS.Store's modelFor method.

modelName is generated for you by Ember Data. It will be a lowercased, dasherized string. For example:

1
2
store.modelFor('post').modelName; // 'post'
store.modelFor('blog-post').modelName; // 'blog-post'

The most common place you'll want to access modelName is in your serializer's payloadKeyFromModelName method. For example, to change payload keys to underscore (instead of dasherized), you might use the following code:

1
2
3
4
5
export default const PostSerializer = DS.RESTSerializer.extend({
  payloadKeyFromModelName: function(modelName) {
    return Ember.String.underscore(modelName);
  }
});

An array of types directly related to a model. Each type will be included once, regardless of the number of relationships it has with the model.

For example, given a model with this definition:

1
2
3
4
5
6
7
8
import DS from 'ember-data';

export default DS.Model.extend({
   users: DS.hasMany('user'),
   owner: DS.belongsTo('user'),

   posts: DS.hasMany('post')
 });

This property would contain the following:

1
2
3
4
5
import Ember from 'ember';
import Blog from 'app/models/blog';

let relatedTypes = Ember.get(Blog, 'relatedTypes');
//=> [ User, Post ]

A hash containing lists of the model's relationships, grouped by the relationship kind. For example, given a model with this definition:

1
2
3
4
5
6
7
8
import DS from 'ember-data';

export default DS.Model.extend({
   users: DS.hasMany('user'),
   owner: DS.belongsTo('user'),

   posts: DS.hasMany('post')
 });

This property would contain the following:

1
2
3
4
5
6
7
8
import Ember from 'ember';
import Blog from 'app/models/blog';

let relationshipNames = Ember.get(Blog, 'relationshipNames');
relationshipNames.hasMany;
//=> ['users', 'posts']
relationshipNames.belongsTo;
//=> ['owner']

The model's relationships as a map, keyed on the type of the relationship. The value of each entry is an array containing a descriptor for each relationship with that type, describing the name of the relationship as well as the type.

For example, given the following model definition:

1
2
3
4
5
6
7
import DS from 'ember-data';

export default DS.Model.extend({
   users: DS.hasMany('user'),
   owner: DS.belongsTo('user'),
   posts: DS.hasMany('post')
 });

This computed property would return a map describing these relationships, like this:

1
2
3
4
5
6
7
8
9
10
11
import Ember from 'ember';
import Blog from 'app/models/blog';
import User from 'app/models/user';
import Post from 'app/models/post';

let relationships = Ember.get(Blog, 'relationships');
relationships.get(User);
//=> [ { name: 'users', kind: 'hasMany' },
//     { name: 'owner', kind: 'belongsTo' } ]
relationships.get(Post);
//=> [ { name: 'posts', kind: 'hasMany' } ]

A map whose keys are the relationships of a model and whose values are relationship descriptors.

For example, given a model with this definition:

1
2
3
4
5
6
7
8
import DS from 'ember-data';

export default DS.Model.extend({
   users: DS.hasMany('user'),
   owner: DS.belongsTo('user'),

   posts: DS.hasMany('post')
 });

This property would contain the following:

1
2
3
4
5
6
7
8
import Ember from 'ember';
import Blog from 'app/models/blog';

let relationshipsByName = Ember.get(Blog, 'relationshipsByName');
relationshipsByName.get('users');
//=> { key: 'users', kind: 'hasMany', type: 'user', options: Object, isRelationship: true }
relationshipsByName.get('owner');
//=> { key: 'owner', kind: 'belongsTo', type: 'user', options: Object, isRelationship: true }

A map whose keys are the attributes of the model (properties described by DS.attr) and whose values are type of transformation applied to each attribute. This map does not include any attributes that do not have an transformation type.

Example

1
2
3
4
5
6
7
import DS from 'ember-data';

export default DS.Model.extend({
   firstName: DS.attr(),
   lastName: DS.attr('string'),
   birthday: DS.attr('date')
 });
1
2
3
4
5
6
7
8
9
10
11
12
import Ember from 'ember';
import Person from 'app/models/person';

let transformedAttributes = Ember.get(Person, 'transformedAttributes')

transformedAttributes.forEach(function(field, type) {
   console.log(field, type);
 });

// prints:
// lastName string
// birthday date