Class 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
Methods
changedAttributes : Object
Defined in packages/ember-data/lib/system/model/model.js:647
- returns
- Object
an object, whose keys are changed properties, and value is an [oldProp, newProp] array.
Returns an object, whose keys are changed properties, and value is an [oldProp, newProp] array.
Example
import DS from 'ember-data';
export default DS.Model.extend({
name: attr('string')
});
var mascot = store.createRecord('mascot');
mascot.changedAttributes(); // {}
mascot.set('name', 'Tomster');
mascot.changedAttributes(); // {name: [undefined, 'Tomster']}
deleteRecord
Defined in packages/ember-data/lib/system/model/model.js:562
Marks the record as deleted but does not save it. You must call
save
afterwards if you want to persist it. You might use this
method if you want to allow the user to still rollbackAttributes()
after a delete it was made.
Example
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
softDelete: function() {
this.controller.get('model').deleteRecord();
},
confirm: function() {
this.controller.get('model').save();
},
undo: function() {
this.controller.get('model').rollbackAttributes();
}
}
});
destroyRecord (options) : Promise
Defined in packages/ember-data/lib/system/model/model.js:594
- options
- Object
- returns
- Promise
a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error.
Same as deleteRecord
, but saves the record immediately.
Example
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
delete: function() {
var controller = this.controller;
controller.get('model').destroyRecord().then(function() {
controller.transitionToRoute('model.index');
});
}
}
});
didDefineProperty (proto, key, value)
Defined in packages/ember-data/lib/system/relationships/ext.js:105
- proto
- Object
- key
- String
- value
- Ember.ComputedProperty
This Ember.js hook allows an object to be notified when a property is defined.
In this case, we use it to be notified when an Ember Data user defines a belongs-to relationship. In that case, we need to set up observers for each one, allowing us to track relationship changes and automatically reflect changes in the inverse has-many array.
This hook passes the class being set up, as well as the key and value being defined. So, for example, when the user does this:
DS.Model.extend({
parent: DS.belongsTo('user')
});
This hook would be called with "parent" as the key and the computed
property returned by DS.belongsTo
as the value.
eachAttribute (callback, binding)
Defined in packages/ember-data/lib/system/model/attributes.js:122
- callback
- Function
The callback to execute
- binding
- Object
the value to which the callback's
this
should be bound
Iterates through the attributes of the model, calling the passed function on each attribute.
The callback method you provide should have the following signature (all parameters are optional):
function(name, meta);
name
the name of the current property in the iterationmeta
the meta object for the attribute property in the iteration
Note that in addition to a callback, you can also pass an optional target
object that will be set as this
on the context.
Example
import DS from 'ember-data';
var Person = DS.Model.extend({
firstName: attr('string'),
lastName: attr('string'),
birthday: attr('date')
});
Person.eachAttribute(function(name, meta) {
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"}
eachRelatedType (callback, binding)
Defined in packages/ember-data/lib/system/relationships/ext.js:562
- callback
- Function
the callback to invoke
- binding
- Any
the value to which the callback's
this
should be bound
Given a callback, iterates over each of the types related to a model, invoking the callback with the related type's class. Each type will be returned just once, regardless of how many different relationships it has with a model.
eachRelationship (callback, binding)
Defined in packages/ember-data/lib/system/relationships/ext.js:546
- callback
- Function
the callback to invoke
- binding
- Any
the value to which the callback's
this
should be bound
Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor.
eachTransformedAttribute (callback, binding)
Defined in packages/ember-data/lib/system/model/attributes.js:171
- callback
- Function
The callback to execute
- binding
- Object
the value to which the callback's
this
should be bound
Iterates through the transformedAttributes of the model, calling the passed function on each attribute. Note the callback will not be called for any attributes that do not have an transformation type.
The callback method you provide should have the following signature (all parameters are optional):
function(name, type);
name
the name of the current property in the iterationtype
a string containing the name of the type of transformed applied to the attribute
Note that in addition to a callback, you can also pass an optional target
object that will be set as this
on the context.
Example
import DS from 'ember-data';
var Person = DS.Model.extend({
firstName: attr(),
lastName: attr('string'),
birthday: attr('date')
});
Person.eachTransformedAttribute(function(name, type) {
console.log(name, type);
});
// prints:
// lastName string
// birthday date
inverseFor (name) : Object
Defined in packages/ember-data/lib/system/relationships/ext.js:194
- name
- String
the name of the relationship
- returns
- Object
the inverse relationship, or null
Find the relationship which is the inverse of the one asked for.
For example, if you define models like this:
import DS from 'ember-data';
export default DS.Model.extend({
comments: DS.hasMany('message')
});
import DS from 'ember-data';
export default DS.Model.extend({
owner: DS.belongsTo('post')
});
App.Post.inverseFor('comments') -> { type: App.Message, name: 'owner', kind: 'belongsTo' } App.Message.inverseFor('owner') -> { type: App.Post, name: 'comments', kind: 'hasMany' }
reload : Promise
Defined in packages/ember-data/lib/system/model/model.js:792
- returns
- Promise
a promise that will be resolved with the record when the adapter returns successfully or rejected if the adapter returns with an error.
Reload the record from the adapter.
This will only work if the record has already finished loading
and has not yet been modified (isLoaded
but not isDirty
,
or isSaving
).
Example
import Ember from 'ember';
export default Ember.Route.extend({
actions: {
reload: function() {
this.controller.get('model').reload().then(function(model) {
// do something with the reloaded model
});
}
}
});
rollbackAttributes
Defined in packages/ember-data/lib/system/model/model.js:732
If the model isDirty
this function will discard any unsaved
changes. If the model isNew
it will be removed from the store.
Example
record.get('name'); // 'Untitled Document'
record.set('name', 'Doc 1');
record.get('name'); // 'Doc 1'
record.rollbackAttributes();
record.get('name'); // 'Untitled Document'
save (options) : Promise
Defined in packages/ember-data/lib/system/model/model.js:764
- options
- Object
- returns
- Promise
a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error.
Save the record and persist any changes to the record to an external source via the adapter.
Example
record.set('name', 'Tomster');
record.save().then(function() {
// Success callback
}, function() {
// Error callback
});
serialize (options) : Object
Defined in packages/ember-data/lib/system/model/model.js:437
- options
- Object
- returns
- Object
an object whose values are primitive JSON values only
Create a JSON representation of the record, using the serialization strategy of the store's adapter.
serialize
takes an optional hash as a parameter, currently
supported options are:
includeId
:true
if the record's ID should be included in the JSON representation.
toJSON (options) : Object
Defined in packages/ember-data/lib/system/model/model.js:455
- options
- Object
- returns
- Object
A JSON representation of the object.
Use DS.JSONSerializer to get the JSON representation of a record.
toJSON
takes an optional hash as a parameter, currently
supported options are:
includeId
:true
if the record's ID should be included in the JSON representation.
typeForRelationship (name, store) : DS.Model
Defined in packages/ember-data/lib/system/relationships/ext.js:164
- name
- String
the name of the relationship
- store
- Store
an instance of DS.Store
- returns
- DS.Model
the type of the relationship, or undefined
For a given relationship name, returns the model type of the relationship.
For example, if you define a model like this:
import DS from 'ember-data';
export default DS.Model.extend({
comments: DS.hasMany('comment')
});
Calling App.Post.typeForRelationship('comments')
will return App.Comment
.
Properties
adapterError
Defined in packages/ember-data/lib/system/model/model.js:428
This property holds the DS.AdapterError
object with which
last adapter operation was rejected.
attributes
Defined in packages/ember-data/lib/system/model/attributes.js:19
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
import DS from 'ember-data';
export default DS.Model.extend({
firstName: attr('string'),
lastName: attr('string'),
birthday: attr('date')
});
import Ember from 'ember';
import Person from 'app/models/person';
var attributes = Ember.get(Person, 'attributes')
attributes.forEach(function(name, meta) {
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"}
dirtyType
Defined in packages/ember-data/lib/system/model/model.js:276
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
var record = store.createRecord('model');
record.get('dirtyType'); // 'created'
errors
Defined in packages/ember-data/lib/system/model/model.js:363
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 backendattribute
The name of the property associated with this error message
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.
<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.
{{#each model.errors.messages as |message|}}
<div class="error">
{{message}}
</div>
{{/each}}
fields
Defined in packages/ember-data/lib/system/relationships/ext.js:491
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:
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')
});
import Ember from 'ember';
import Blog from 'app/models/blog';
var fields = Ember.get(Blog, 'fields');
fields.forEach(function(kind, field) {
console.log(field, kind);
});
// prints:
// users, hasMany
// owner, belongsTo
// posts, hasMany
// title, attribute
hasDirtyAttributes
Defined in packages/ember-data/lib/system/model/model.js:156
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
var record = store.createRecord('model');
record.get('hasDirtyAttributes'); // true
store.find('model', 1).then(function(model) {
model.get('hasDirtyAttributes'); // false
model.set('foo', 'some value');
model.get('hasDirtyAttributes'); // true
});
id
Defined in packages/ember-data/lib/system/model/model.js:336
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.
var record = store.createRecord('model');
record.get('id'); // null
store.find('model', 1).then(function(model) {
model.get('id'); // '1'
});
isDeleted
Defined in packages/ember-data/lib/system/model/model.js:205
If this property is true
the record is in the deleted
state
and has been marked for deletion. When isDeleted
is true and
isDirty
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 isDirty
and isSaving
are false, the
change has persisted.
Example
var record = store.createRecord('model');
record.get('isDeleted'); // false
record.deleteRecord();
// Locally deleted
record.get('isDeleted'); // true
record.get('isDirty'); // true
record.get('isSaving'); // false
// Persisting the deletion
var 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('isDirty'); // false
});
isEmpty
Defined in packages/ember-data/lib/system/model/model.js:62
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.
isError
Defined in packages/ember-data/lib/system/model/model.js:298
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
record.get('isError'); // false
record.set('foo', 'valid value');
record.save().then(null, function() {
record.get('isError'); // true
});
isLoaded
Defined in packages/ember-data/lib/system/model/model.js:87
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
var record = store.createRecord('model');
record.get('isLoaded'); // true
store.find('model', 1).then(function(model) {
model.get('isLoaded'); // true
});
isLoading
Defined in packages/ember-data/lib/system/model/model.js:76
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.
isNew
Defined in packages/ember-data/lib/system/model/model.js:243
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
var record = store.createRecord('model');
record.get('isNew'); // true
record.save().then(function(model) {
model.get('isNew'); // false
});
isReloading
Defined in packages/ember-data/lib/system/model/model.js:319
If true
the store is attempting to reload the record form the adapter.
Example
record.get('isReloading'); // false
record.reload();
record.get('isReloading'); // true
isSaving
Defined in packages/ember-data/lib/system/model/model.js:182
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
var record = store.createRecord('model');
record.get('isSaving'); // false
var promise = record.save();
record.get('isSaving'); // true
promise.then(function() {
record.get('isSaving'); // false
});
isValid
Defined in packages/ember-data/lib/system/model/model.js:265
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.
modelName
Defined in packages/ember-data/lib/system/model/model.js:905
Represents the model's class name as a string. This can be used to look up the model through DS.Store's modelFor method.
modelName
is generated for you by Ember Data. It will be a lowercased, dasherized string.
For example:
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:
export default var PostSerializer = DS.RESTSerializer.extend({
payloadKeyFromModelName: function(modelName) {
return Ember.String.underscore(modelName);
}
});
relatedTypes
Defined in packages/ember-data/lib/system/relationships/ext.js:418
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:
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:
import Ember from 'ember';
import Blog from 'app/models/blog';
var relatedTypes = Ember.get(Blog, 'relatedTypes');
//=> [ App.User, App.Post ]
relationshipNames
Defined in packages/ember-data/lib/system/relationships/ext.js:369
A hash containing lists of the model's relationships, grouped by the relationship kind. For example, given a model with this definition:
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:
import Ember from 'ember';
import Blog from 'app/models/blog';
var relationshipNames = Ember.get(Blog, 'relationshipNames');
relationshipNames.hasMany;
//=> ['users', 'posts']
relationshipNames.belongsTo;
//=> ['owner']
relationships
Defined in packages/ember-data/lib/system/relationships/ext.js:328
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:
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:
import Ember from 'ember';
import Blog from 'app/models/blog';
var relationships = Ember.get(Blog, 'relationships');
relationships.get(App.User);
//=> [ { name: 'users', kind: 'hasMany' },
// { name: 'owner', kind: 'belongsTo' } ]
relationships.get(App.Post);
//=> [ { name: 'posts', kind: 'hasMany' } ]
relationshipsByName
Defined in packages/ember-data/lib/system/relationships/ext.js:453
A map whose keys are the relationships of a model and whose values are relationship descriptors.
For example, given a model with this definition:
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:
import Ember from 'ember';
import Blog from 'app/models/blog';
var relationshipsByName = Ember.get(Blog, 'relationshipsByName');
relationshipsByName.get('users');
//=> { key: 'users', kind: 'hasMany', type: App.User }
relationshipsByName.get('owner');
//=> { key: 'owner', kind: 'belongsTo', type: App.User }
transformedAttributes
Defined in packages/ember-data/lib/system/model/attributes.js:72
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
import DS from 'ember-data';
export default DS.Model.extend({
firstName: attr(),
lastName: attr('string'),
birthday: attr('date')
});
import Ember from 'ember';
import Person from 'app/models/person';
var transformedAttributes = Ember.get(Person, 'transformedAttributes')
transformedAttributes.forEach(function(field, type) {
console.log(field, type);
});
// prints:
// lastName string
// birthday date
Events
becameError
Defined in packages/ember-data/lib/system/model/model.js:520
Fired when the record enters the error state.
becameInvalid
Defined in packages/ember-data/lib/system/model/model.js:513
Fired when the record becomes invalid.
didCreate
Defined in packages/ember-data/lib/system/model/model.js:499
Fired when a new record is commited to the server.
didDelete
Defined in packages/ember-data/lib/system/model/model.js:506
Fired when the record is deleted.
didLoad
Defined in packages/ember-data/lib/system/model/model.js:485
Fired when the record is loaded from the server.
didUpdate
Defined in packages/ember-data/lib/system/model/model.js:492
Fired when the record is updated.
ready
Defined in packages/ember-data/lib/system/model/model.js:477
Fired when the record is ready to be interacted with, that is either loaded from the server or created locally.
rolledBack
Defined in packages/ember-data/lib/system/model/model.js:527
Fired when the record is rolled back.