Class Model

public

Base class from which Models can be defined.

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

export default class User extends Model {
  @attr name;
}

Models are used both to define the static schema for a particular resource type as well as the class to instantiate to present that data from cache.

Show:

Available since v2.5.0

name
String

of the relationship

returns
BelongsToReference

reference for this relationship

Get the reference for the specified belongsTo relationship.

For instance, given the following model

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

export default class BlogPost extends Model {
  @belongsTo('user', { async: true, inverse: null }) author;
}

Then the reference for the author relationship would be retrieved from a record instance like so:

blogPost.belongsTo('author');

A BelongsToReference is a low-level API that allows access and manipulation of a belongsTo relationship.

It is especially useful when you're dealing with async relationships as it allows synchronous access to the relationship data if loaded, as well as APIs for loading, reloading the data or accessing available information without triggering a load.

It may also be useful when using sync relationships that need to be loaded/reloaded with more precise timing than marking the relationship as async and relying on autofetch would have allowed.

However,keep in mind that marking a relationship as async: false will introduce bugs into your application if the data is not always guaranteed to be available by the time the relationship is accessed. Ergo, it is recommended when using this approach to utilize links for unloaded relationship state instead of identifiers.

Reference APIs are entangled with the relationship's underlying state, thus any getters or cached properties that utilize these will properly invalidate if the relationship state changes.

References are "stable", meaning that multiple calls to retrieve the reference for a given relationship will always return the same HasManyReference.

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

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

export default class MascotModel extends Model {
  @attr('string') name;
  @attr('boolean', {
    defaultValue: false
  })
  isAdmin;
}
let mascot = store.createRecord('mascot');

mascot.changedAttributes(); // {}

mascot.set('name', 'Tomster');
mascot.changedAttributes(); // { name: [undefined, 'Tomster'] }

mascot.set('isAdmin', true);
mascot.changedAttributes(); // { isAdmin: [undefined, true], name: [undefined, 'Tomster'] }

mascot.save().then(function() {
  mascot.changedAttributes(); // {}

  mascot.set('isAdmin', false);
  mascot.changedAttributes(); // { isAdmin: [true, false] }
});

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

import Component from '@glimmer/component';

export default class extends Component {
  softDelete = () => {
    this.args.model.deleteRecord();
  }

  confirm = () => {
    this.args.model.save();
  }

  undo = () => {
    this.args.model.rollbackAttributes();
  }
}
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 Component from '@glimmer/component';

export default class extends Component {
  delete = () => {
    this.args.model.destroyRecord().then(function() {
      this.transitionToRoute('model.index');
    });
  }
}

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

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

export default class PostAdapter extends MyCustomAdapter {
  deleteRecord(store, type, snapshot) {
    if (snapshot.adapterOptions.subscribe) {
      // ...
    }
    // ...
  }
}
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

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

class PersonModel extends Model {
   @attr('string') firstName;
   @attr('string') lastName;
   @attr('date') birthday;
 }

PersonModel.eachAttribute(function(name, meta) {
   // do thing
 });

// prints:
// firstName {type: "string", kind: 'attribute', options: Object, parentType: function, name: "firstName"}
// lastName {type: "string", kind: 'attribute', options: Object, parentType: function, name: "lastName"}
// birthday {type: "date", kind: 'attribute', options: Object, parentType: function, name: "birthday"}
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.

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.

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

Available since v2.5.0

name
String

of the relationship

returns
HasManyReference

reference for this relationship

Get the reference for the specified hasMany relationship.

For instance, given the following model

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

export default class BlogPost extends Model {
  @hasMany('comment', { async: true, inverse: null }) comments;
}

Then the reference for the comments relationship would be retrieved from a record instance like so:

blogPost.hasMany('comments');

A HasManyReference is a low-level API that allows access and manipulation of a hasMany relationship.

It is especially useful when you are dealing with async relationships as it allows synchronous access to the relationship data if loaded, as well as APIs for loading, reloading the data or accessing available information without triggering a load.

It may also be useful when using sync relationships with @ember-data/model that need to be loaded/reloaded with more precise timing than marking the relationship as async and relying on autofetch would have allowed.

However,keep in mind that marking a relationship as async: false will introduce bugs into your application if the data is not always guaranteed to be available by the time the relationship is accessed. Ergo, it is recommended when using this approach to utilize links for unloaded relationship state instead of identifiers.

Reference APIs are entangled with the relationship's underlying state, thus any getters or cached properties that utilize these will properly invalidate if the relationship state changes.

References are "stable", meaning that multiple calls to retrieve the reference for a given relationship will always return the same HasManyReference.

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:

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

export default class PostModel extends Model {
   @hasMany('message') comments;
 }
app/models/message.js
import Model, { belongsTo } from '@ember-data/model';

export default class MessageModel extends Model {
   @belongsTo('post') owner;
 }
store.modelFor('post').inverseFor('comments', store) // { type: 'message', name: 'owner', kind: 'belongsTo' }
store.modelFor('message').inverseFor('owner', store) // { type: 'post', name: 'comments', kind: 'hasMany' }
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

import Component from '@glimmer/component';

export default class extends Component {
  async reload = () => {
    await this.args.model.reload();
    // do something with the reloaded model
  }
}

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'
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) {
      // ...
    }
    // ...
  }
}
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.

Returns the name of the model class.

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:

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

export default class PostModel extends Model {
  @hasMany('comment') comments;
}

Calling store.modelFor('post').typeForRelationship('comments', store) will return Comment.

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