Class Model
In EmberData a Model
is a class defining the attributes and relationships
of a specific resource type
(model name). In this sense it represents a static "schema".
Data for individual resources fetched from your API is presented
to the UI via instances of the Model
s you define.
An instantiated Model
is referred to as a record
.
When we refer to the ModelClass
we are referring to the class definition
and the static schema methods present on it.
When we refer to a record
we refer to a specific class instance presenting
the resource data for a given type
and id
.
Defining a Model
app/models/person.js | |
1 2 3 4 5 6 7 8 9 |
import Model, { attr, belongsTo, hasMany } from '@ember-data/model'; export default Model.extend({ name: attr(), dog: belongsTo('pet', { inverse: 'owners', async: false }), friends: hasMany('person', { inverse: 'friends', async: true }), }); |
modelName convention
By convention, the name of a given model (its type
) matches the name
of the file in the app/models
folder and should be lowercase, singular
and dasherized.
@mainName @ember-data/model
@tag main
belongsTo (name) BelongsToReference
Defined in ../model/addon/-private/model.js:997
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
app/models/blog.js | |
1 2 3 4 5 |
import Model, { belongsTo } from '@ember-data/model'; export default Model.extend({ user: belongsTo({ async: true }) }); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 |
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
Defined in ../model/addon/-private/model.js:812
- 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 | |
1 2 3 4 5 6 7 8 |
import Model, { attr } from '@ember-data/model'; export default Model.extend({ name: attr('string'), isAdmin: attr('boolean', { defaultValue: false }) }); |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
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
Defined in ../model/addon/-private/model.js:701
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
app/routes/model/delete.js | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
import Route from '@ember/routing/route'; export default Route.extend({ actions: { softDelete() { this.get('controller.model').deleteRecord(); }, confirm() { this.get('controller.model').save(); }, undo() { this.get('controller.model').rollbackAttributes(); } } }); |
destroyRecord (options) Promise
Defined in ../model/addon/-private/model.js:733
- 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
app/routes/model/delete.js | |
1 2 3 4 5 6 7 8 9 10 11 |
import Route from '@ember/routing/route'; export default Route.extend({ actions: { delete() { this.get('controller.model').destroyRecord().then(function() { controller.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
1 |
record.destroyRecord({ adapterOptions: { subscribe: false } }); |
app/adapters/post.js | |
1 2 3 4 5 6 7 8 9 10 |
import MyCustomAdapter from './custom-adapter'; export default MyCustomAdapter.extend({ deleteRecord(store, type, snapshot) { if (snapshot.adapterOptions.subscribe) { // ... } // ... } }); |
eachAttribute (callback, binding)
Defined in ../model/addon/-private/model.js:2112
- 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):
1 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
import Model, { attr } from '@ember-data/model'; let Person = 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 ../model/addon/-private/model.js:1964
- 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 ../model/addon/-private/model.js:1948
- 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 ../model/addon/-private/model.js:2161
- 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):
1 |
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
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
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
Defined in ../model/addon/-private/model.js:1064
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
app/models/blog.js | |
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 |
import Model, { hasMany } from '@ember-data/model'; export default Model.extend({ comments: hasMany({ async: true }) }); 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
Defined in ../model/addon/-private/model.js:1581
- 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 | |
1 2 3 4 5 |
import Model, { hasMany } from '@ember-data/model'; export default Model.extend({ comments: hasMany('message') }); |
app/models/message.js | |
1 2 3 4 5 |
import Model, { belongsTo } from '@ember-data/model'; export default Model.extend({ owner: belongsTo('post') }); |
1 2 |
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
Defined in ../model/addon/-private/model.js:948
- 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
app/routes/model/view.js | |
1 2 3 4 5 6 7 8 9 10 11 |
import Route from '@ember/routing/route'; export default Route.extend({ actions: { reload() { this.controller.get('model').reload().then(function(model) { // do something with the reloaded model }); } } }); |
rollbackAttributes
Defined in ../model/addon/-private/model.js:860
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
1 2 3 4 5 |
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 ../model/addon/-private/model.js:902
- 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
1 2 3 4 5 6 |
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.
1 |
record.save({ adapterOptions: { subscribe: false } }); |
app/adapters/post.js | |
1 2 3 4 5 6 7 8 9 10 |
import MyCustomAdapter from './custom-adapter'; export default MyCustomAdapter.extend({ updateRecord(store, type, snapshot) { if (snapshot.adapterOptions.subscribe) { // ... } // ... } }); |
serialize (options) Object
Defined in ../model/addon/-private/model.js:606
- 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 ../model/addon/-private/model.js:1323
- options
- Object
- returns
- Object
- A JSON representation of the object.
Use 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.
toString
Defined in ../model/addon/-private/model.js:2211
Returns the name of the model class.
typeForRelationship (name, store) Model
Defined in ../model/addon/-private/model.js:1551
- 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 | |
1 2 3 4 5 |
import Model, { hasMany } from '@ember-data/model'; export default Model.extend({ comments: hasMany('comment') }); |
Calling store.modelFor('post').typeForRelationship('comments', store)
will return Comment
.
unloadRecord
Defined in ../model/addon/-private/model.js:782
Unloads the record from the store. This will not send a delete request to your server, it just unloads the record from memory.