home
  • Blog
  • Home
  • Projects
    • Ember
    • EmberData
    • Ember CLI
4.12
  • Packages
    • @ember-data/adapter
    • @ember-data/adapter/error
    • @ember-data/adapter/json-api
    • @ember-data/adapter/rest
    • @ember-data/canary-features
    • @ember-data/debug
    • @ember-data/deprecations
    • @ember-data/experimental-preview-types
    • @ember-data/graph
    • @ember-data/json-api
    • @ember-data/legacy-compat
    • @ember-data/model
    • @ember-data/request
    • @ember-data/request/fetch
    • @ember-data/serializer
    • @ember-data/serializer/json
    • @ember-data/serializer/json-api
    • @ember-data/serializer/rest
    • @ember-data/store
    • @ember-data/tracking
  • Classes
    • <Interface> Adapter
    • <Interface> Cache
    • <Interface> Handler
    • <Interface> Serializer
    • AbortError
    • Adapter
    • AdapterError
    • BelongsToReference
    • BooleanTransform
    • BuildURLMixin
    • Cache
    • CacheManager
    • CacheStoreWrapper
    • CanaryFeatureFlags
    • ConflictError
    • CurrentDeprecations
    • DateTransform
    • DebugLogging
    • EmbeddedRecordsMixin
    • Errors
    • Fetch
    • ForbiddenError
    • Future
    • HasManyReference
    • IdentifierCache
    • InvalidError
    • JSONAPIAdapter
    • JSONAPISerializer
    • JSONSerializer
    • ManyArray
    • Model
    • NotFoundError
    • NotificationManager
    • NumberTransform
    • PromiseArray
    • PromiseManyArray
    • PromiseObject
    • RESTAdapter
    • RESTSerializer
    • RecordArray
    • RecordReference
    • RequestManager
    • RequestStateService
    • SchemaService
    • Serializer
    • ServerError
    • Snapshot
    • SnapshotRecordArray
    • StableRecordIdentifier
    • Store
    • StringTransform
    • TimeoutError
    • Transform
    • UnauthorizedError

Class Model public


Extends: Ember.EmberObject
Defined in: ../model/src/-private/model.js:109
Module: @ember-data/model

Base class from which Models can be defined.

```js import Model, { attr } from '@ember-data/model';

export default class User extends Model {


Methods

belongsTo (name) : BelongsToReference public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:1003

Available since v2.5.0

name
String

of the relationship

returns
BelongsToReference

reference for this relationship

Get the reference for the specified belongsTo relationship.

Example

```js {data-filename=app/models/blog.js} import Model, { belongsTo } from '@ember-data/model';

export default class BlogModel extends Model {

changedAttributes : Object public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:784

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.

The array represents the diff of the canonical state with the local state of the model. Note: if the model is created locally, the canonical state is empty since the adapter hasn't acknowledged the attributes yet:

Example

```js {data-filename=app/models/mascot.js} import Model, { attr } from '@ember-data/model';

export default class MascotModel extends Model {

deleteRecord public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:654

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 was made.

Example

```js {data-filename=app/controllers/model/delete.js} import Controller from '@ember/controller'; import { action } from '@ember/object';

export default class ModelDeleteController extends Controller {

destroyRecord (options) : Promise public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:694

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

```js {data-filename=app/controllers/model/delete.js} import Controller from '@ember/controller'; import { action } from '@ember/object';

export default class ModelDeleteController extends Controller {

eachAttribute (callback, binding) public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:2233

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 iteration
  • meta 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

```javascript import Model, { attr } from '@ember-data/model';

class PersonModel extends Model {

eachRelatedType (callback, binding) public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:2012

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) public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:1978

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) public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:2300

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 iteration
  • type 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 Model, { attr } from '@ember-data/model';

let Person = Model.extend({
   firstName: attr(),
   lastName: attr('string'),
   birthday: attr('date')
 });

Person.eachTransformedAttribute(function(name, type) {
   // do thing
 });

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

hasMany (name) : HasManyReference public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:1071

Available since v2.5.0

name
String

of the relationship

returns
HasManyReference

reference for this relationship

Get the reference for the specified hasMany relationship.

Example

```js {data-filename=app/models/blog.js} import Model, { hasMany } from '@ember-data/model';

export default class BlogModel extends Model {

inverseFor (name, store) : Object public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:1332

name
String

the name of the relationship

store
Store
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:

```js {data-filename=app/models/post.js} import Model, { hasMany } from '@ember-data/model';

export default class PostModel extends Model {

reload (options) : Promise public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:939

options
Object

optional, may include adapterOptions hash which will be passed to adapter request

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.

Example

```js {data-filename=app/controllers/model/view.js} import Controller from '@ember/controller'; import { action } from '@ember/object';

export default class ViewController extends Controller {

rollbackAttributes public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:834

Available since v1.13.0

If the model hasDirtyAttributes this function will discard any unsaved changes. If the model isNew it will be removed from the store.

Example

record.name; // 'Untitled Document'
record.set('name', 'Doc 1');
record.name; // 'Doc 1'
record.rollbackAttributes();
record.name; // 'Untitled Document'

save (options) : Promise public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:882

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
});

If you pass an object using the adapterOptions property of the options argument it will be passed to your adapter via the snapshot.

record.save({ adapterOptions: { subscribe: false } });
app/adapters/post.js
import MyCustomAdapter from './custom-adapter';

export default class PostAdapter extends MyCustomAdapter {
  updateRecord(store, type, snapshot) {
    if (snapshot.adapterOptions.subscribe) {
      // ...
    }
    // ...
  }
}

serialize (options) : Object public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:619

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.

toString public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:2368

Returns the name of the model class.

typeForRelationship (name, store) : Model public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:1266

name
String

the name of the relationship

store
Store

an instance of Store

returns
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:

```js {data-filename=app/models/post.js} import Model, { hasMany } from '@ember-data/model';

export default class PostModel extends Model {

unloadRecord public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:753

Unloads the record from the store. This will not send a delete request to your server, it just unloads the record from memory.

Properties

adapterError public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:603

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

attributes public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:2088

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

Example

```js {data-filename=app/models/person.js} import Model, { attr } from '@ember-data/model';

export default class PersonModel extends Model {

dirtyType public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:386

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

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

errors public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:544

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
record.errors.length; // 0
record.set('foo', 'invalid value');
record.save().catch(function() {
  record.errors.foo;
  // [{message: 'foo should be a number.', attribute: 'foo'}]
});

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

<label>Username: <Input @value={{@model.username}} /> </label>
{{#each @model.errors.username as |error|}}
  <div class="error">
    {{error.message}}
  </div>
{{/each}}
<label>Email: <Input @value={{@model.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 public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:1903

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:

```js {data-filename=app/models/blog.js} import Model, { attr, belongsTo, hasMany } from '@ember-data/model';

export default class BlogModel extends Model {

hasDirtyAttributes public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:242

Available since v1.13.0

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

let record = store.createRecord('model');
record.hasDirtyAttributes; // true

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

id public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:460

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.

let record = store.createRecord('model');
record.id; // null

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

isDeleted public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:300

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

let record = store.createRecord('model');
record.isDeleted;    // false
record.deleteRecord();

// Locally deleted
record.isDeleted;           // true
record.hasDirtyAttributes;  // true
record.isSaving;            // false

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

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

isEmpty public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:180

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 public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:412

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.isError; // false
record.set('foo', 'valid value');
record.save().then(null, function() {
  record.isError; // true
});

isLoaded public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:215

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

let record = store.createRecord('model');
record.isLoaded; // true

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

isLoading public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:199

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 public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:343

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

let record = store.createRecord('model');
record.isNew; // true

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

isReloading public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:442

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

Example

record.isReloading; // false
record.reload();
record.isReloading; // true

isSaving public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:272

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

let record = store.createRecord('model');
record.isSaving; // false
let promise = record.save();
record.isSaving; // true
promise.then(function() {
  record.isSaving; // false
});

isValid public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:370

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 public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:1216

Represents the model's class name as a string. This can be used to look up the model's class name through 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:

import RESTSerializer from '@ember-data/serializer/rest';
import { underscore } from '<app-name>/utils/string-utils';

export default const PostSerializer = RESTSerializer.extend({
  payloadKeyFromModelName(modelName) {
    return underscore(modelName);
  }
});

relatedTypes public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:1723

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:

```js {data-filename=app/models/blog.js} import Model, { belongsTo, hasMany } from '@ember-data/model';

export default class BlogModel extends Model {

relationshipNames public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:1655

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

```js {data-filename=app/models/blog.js} import Model, { belongsTo, hasMany } from '@ember-data/model';

export default class BlogModel extends Model {

relationships public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:1577

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:

```js {data-filename=app/models/blog.js} import Model, { belongsTo, hasMany } from '@ember-data/model';

export default class BlogModel extends Model {

relationshipsByName public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:1796

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

For example, given a model with this definition:

```js {data-filename=app/models/blog.js} import Model, { belongsTo, hasMany } from '@ember-data/model';

export default class BlogModel extends Model {

store public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:537

The store service instance which created this record instance

transformedAttributes public

Module: @ember-data/model

Defined in ../packages/model/src/-private/model.js:2164

A map whose keys are the attributes of the model (properties described by 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

```js {data-filename=app/models/person.js} import Model, { attr } from '@ember-data/model';

export default class PersonModel extends Model {

On this page


Methods

  • belongsTo
  • changedAttributes
  • deleteRecord
  • destroyRecord
  • eachAttribute
  • eachRelatedType
  • eachRelationship
  • eachTransformedAttribute
  • hasMany
  • inverseFor
  • reload
  • rollbackAttributes
  • save
  • serialize
  • toString
  • typeForRelationship
  • unloadRecord

Properties

  • adapterError
  • attributes
  • dirtyType
  • errors
  • fields
  • hasDirtyAttributes
  • id
  • isDeleted
  • isEmpty
  • isError
  • isLoaded
  • isLoading
  • isNew
  • isReloading
  • isSaving
  • isValid
  • modelName
  • relatedTypes
  • relationshipNames
  • relationships
  • relationshipsByName
  • store
  • transformedAttributes
Team Sponsors Security Legal Branding Community Guidelines
Twitter GitHub Discord Mastodon

If you want help you can contact us by email, open an issue, or get realtime help by joining the Ember Discord.

© Copyright 2025 - Tilde Inc.
Ember.js is free, open source and always will be.


Ember is generously supported by
blue Created with Sketch.