Class Model
publicBase class from which Models can be define.
import Model, { attr } from '@ember-data/model';
export default class User extends Model {
@attr name;
}
belongsTo (name) BelongsToReference public
Defined in ../model/addon/-private/model.js:921
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
import Model, { belongsTo } from '@ember-data/model';
export default class BlogModel extends Model {
@belongsTo({ async: true }) user;
}
let blog = store.push({
data: {
type: 'blog',
id: 1,
relationships: {
user: {
data: { type: 'user', id: 1 }
}
}
}
});
let userRef = blog.belongsTo('user');
// check if the user relationship is loaded
let isLoaded = userRef.value() !== null;
// get the record of the reference (null if not yet available)
let user = userRef.value();
// get the identifier of the reference
if (userRef.remoteType() === "id") {
let id = userRef.id();
} else if (userRef.remoteType() === "link") {
let link = userRef.link();
}
// load user (via store.findRecord or store.findBelongsTo)
userRef.load().then(...)
// or trigger a reload
userRef.reload().then(...)
// provide data for reference
userRef.push({
type: 'user',
id: 1,
attributes: {
username: "@user"
}
}).then(function(user) {
userRef.value() === user;
});
changedAttributes Object public
Defined in ../model/addon/-private/model.js:727
- 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
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] }
});
deleteRecord public
Defined in ../model/addon/-private/model.js:604
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 Controller from '@ember/controller';
import { action } from '@ember/object';
export default class ModelDeleteController extends Controller {
@action
softDelete() {
this.model.deleteRecord();
}
@action
confirm() {
this.model.save();
}
@action
undo() {
this.model.rollbackAttributes();
}
}
destroyRecord (options) Promise public
Defined in ../model/addon/-private/model.js:641
- 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 Controller from '@ember/controller';
import { action } from '@ember/object';
export default class ModelDeleteController extends Controller {
@action
delete() {
this.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 } });
import MyCustomAdapter from './custom-adapter';
export default class PostAdapter extends MyCustomAdapter {
deleteRecord(store, type, snapshot) {
if (snapshot.adapterOptions.subscribe) {
// ...
}
// ...
}
}
eachAttribute (callback, binding) public
Defined in ../model/addon/-private/model.js:1826
- 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 Model, { attr } from '@ember-data/model';
class PersonModel extends Model {
@attr('string') firstName;
@attr('string') lastName;
@attr('date') birthday;
}
PersonModel.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) public
Defined in ../model/addon/-private/model.js:1673
- 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
Defined in ../model/addon/-private/model.js:1052
- 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.
The callback method you provide should have the following signature (all parameters are optional):
function(name, descriptor);
name
the name of the current property in the iterationdescriptor
the meta object that describes this relationship
The relationship descriptor argument is an object with the following properties.
- key String the name of this relationship on the Model
- kind String "hasMany" or "belongsTo"
- options Object the original options hash passed when the relationship was declared
- parentType Model the type of the Model that owns this relationship
- type String the type name of the related Model
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 JSONSerializer from '@ember-data/serializer/json';
export default class ApplicationSerializer extends JSONSerializer {
serialize(record, options) {
let json = {};
record.eachRelationship(function(name, descriptor) {
if (descriptor.kind === 'hasMany') {
let serializedHasManyName = name.toUpperCase() + '_IDS';
json[serializedHasManyName] = record.get(name).mapBy('id');
}
});
return json;
}
}
eachTransformedAttribute (callback, binding) public
Defined in ../model/addon/-private/model.js:1876
- 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 Model, { attr } from '@ember-data/model';
let Person = Model.extend({
firstName: attr(),
lastName: attr('string'),
birthday: attr('date')
});
Person.eachTransformedAttribute(function(name, type) {
console.log(name, type);
});
// prints:
// lastName string
// birthday date
hasMany (name) HasManyReference public
Defined in ../model/addon/-private/model.js:989
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
import Model, { hasMany } from '@ember-data/model';
export default class BlogModel extends Model {
@hasMany({ async: true }) comments;
}
let blog = store.push({
data: {
type: 'blog',
id: 1,
relationships: {
comments: {
data: [
{ type: 'comment', id: 1 },
{ type: 'comment', id: 2 }
]
}
}
}
});
let commentsRef = blog.hasMany('comments');
// check if the comments are loaded already
let isLoaded = commentsRef.value() !== null;
// get the records of the reference (null if not yet available)
let comments = commentsRef.value();
// get the identifier of the reference
if (commentsRef.remoteType() === "ids") {
let ids = commentsRef.ids();
} else if (commentsRef.remoteType() === "link") {
let link = commentsRef.link();
}
// load comments (via store.findMany or store.findHasMany)
commentsRef.load().then(...)
// or trigger a reload
commentsRef.reload().then(...)
// provide data for reference
commentsRef.push([{ type: 'comment', id: 1 }, { type: 'comment', id: 2 }]).then(function(comments) {
commentsRef.value() === comments;
});
inverseFor (name, store) Object public
Defined in ../model/addon/-private/model.js:1216
- 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:
import Model, { hasMany } from '@ember-data/model';
export default class PostModel extends Model {
@hasMany('message') comments;
}
import Model from '@ember-data/model';
import { belongsTo } from '@ember-decorators/data';
export default class MessageModel extends Model {
@belongsTo('post') owner;
}
store.modelFor('post').inverseFor('comments', store) // { type: App.Message, name: 'owner', kind: 'belongsTo' }
store.modelFor('message').inverseFor('owner', store) // { type: App.Post, name: 'comments', kind: 'hasMany' }
reload (options) Promise public
Defined in ../model/addon/-private/model.js:865
- 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 Controller from '@ember/controller';
import { action } from '@ember/object';
export default class ViewController extends Controller {
@action
reload() {
this.model.reload().then(function(model) {
// do something with the reloaded model
});
}
}
rollbackAttributes public
Defined in ../model/addon/-private/model.js:777
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.get('name'); // 'Untitled Document'
record.set('name', 'Doc 1');
record.get('name'); // 'Doc 1'
record.rollbackAttributes();
record.get('name'); // 'Untitled Document'
save (options) Promise public
Defined in ../model/addon/-private/model.js:815
- 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 } });
import MyCustomAdapter from './custom-adapter';
export default class PostAdapter extends MyCustomAdapter {
updateRecord(store, type, snapshot) {
if (snapshot.adapterOptions.subscribe) {
// ...
}
// ...
}
}
serialize (options) Object public
Defined in ../model/addon/-private/model.js:569
- 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
Defined in ../model/addon/-private/model.js:1927
Returns the name of the model class.
typeForRelationship (name, store) Model public
Defined in ../model/addon/-private/model.js:1184
- 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:
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
.
unloadRecord public
Defined in ../model/addon/-private/model.js:696
Unloads the record from the store. This will not send a delete request to your server, it just unloads the record from memory.