Ember Data
Ember Data is a library for robustly managing model data in your
Ember.js applications.
Ember Data is designed to be agnostic to the underlying persistence
mechanism, so it works just as well with JSON APIs over HTTP as it does
with streaming WebSockets or local IndexedDB storage.
It provides many of the facilities you'd find in server-side ORMs like
ActiveRecord, but is designed specifically for the unique environment of
JavaScript in the browser.
In particular, Ember Data uses Promises/A+-compatible promises from the
ground up to manage loading and saving records, so integrating with
other JavaScript APIs is easy.
Using Ember Data
Getting Ember Data
bower install ember-data --save
The latest passing build from the "master" branch is available on
http://emberjs.com/builds/#/canary.
Similarly, the latest passing build from the "beta" branch can be found
on http://emberjs.com/builds/#/beta
Or build ember-data.js yourself. Clone the repository and run npm run dist
after setup. You'll find ember-data.js in the dist
directory.
Internet Explorer 8
Internet Explorer 8 support requires Ember 1.8.1 (which provides a polyfill for Object.create
).
Instantiating the Store
In Ember Data, the store is responsible for managing the lifecycle of
your models. Every time you need a model or a collection of models,
you'll ask the store for it.
To create a store, you don't need to do anything. Just by loading the
Ember Data library, all of the routes and controllers in your
application will get a new store
property. This property is an
instance of DS.Store
that will be shared across all of the routes and
controllers in your app.
Defining Your Models
First thing's first: tell Ember Data about the models in your
application. For example, imagine we're writing a blog reader app.
Here's what your model definition would look like if you're using
globals (that is, not something like Ember App Kit or ember-cli):
var attr = DS.attr;
var hasMany = DS.hasMany;
var belongsTo = DS.belongsTo;
App.BlogPost = DS.Model.extend({
title: attr(),
createdAt: attr('date'),
comments: hasMany('comment')
});
App.Comment = DS.Model.extend({
body: attr(),
username: attr(),
post: belongsTo('blogPost')
});
If you're using ES6 modules (via Ember App Kit or ember-cli), your
models would look like this:
var attr = DS.attr;
var hasMany = DS.hasMany;
export default DS.Model.extend({
title: attr(),
createdAt: attr('date'),
comments: hasMany('comment')
});
var attr = DS.attr;
var belongsTo = DS.belongsTo;
export default DS.Model.extend({
body: attr(),
username: attr(),
post: belongsTo('blogPost')
});
A Brief Note on Adapters
Without immediately diving in to the depths of the architecture, one
thing you should know is that Ember Data uses an object called an
adapter to know how to talk to your server.
An adapter is just an object that knows how to translate requests from
Ember Data into requests on your server. For example, if I ask the Ember
Data store for a record of type person
with an ID of 123
, the
adapter translates that into an XHR request to (for example)
api.example.com/v3/person/123.json
.
By default, Ember Data will use the RESTAdapter
, which adheres to a
set of RESTful JSON conventions.
Ember Data also ships with the FixtureAdapter
, useful for testing and
prototyping before you have a server, and the ActiveModelAdapter
,
which is designed to work out-of-the-box with the
ActiveModel::Serializers
gem for Rails.
To learn more about adapters, including what conventions the
RESTAdapter
follows and how to build your own, see the Ember.js
Guides: Connecting to an HTTP
Server.
Fetching a Collection of Models
From your route or controller:
this.store.find('blogPost');
This returns a promise that resolves to the collection of records.
Fetching a Single Model
this.store.find('blogPost', 123);
This returns a promise that resolves to the requested record. If the
record can't be found or there was an error during the request, the
promise will be rejected.
Even More Documentation
For much more detail on how to use Ember Data, see the Ember.js Guides
on models.
API Stability
Ember Data is still under active development and is currently beta
quality. That being said, the API has largely stabilized and many
companies are using it in production.
For details on anticipated changes before the 1.0 release, see the blog
post The Road to Ember Data
1.0.
Building Ember Data
- Ensure that Node.js is installed.
- Run
npm install
to ensure the required dependencies are installed. - Run
npm run dist
to build Ember Data. The builds will be placed in the dist/
directory.
Contribution
See CONTRIBUTING.md
How to Run Unit Tests
Setup
-
Install Node.js from http://nodejs.org or your favorite package manager.
-
Install Ember CLI and bower. npm install -g ember-cli bower
-
Run npm install
inside the project root to install the JS dependencies.
In Your Browser
-
To start the development server, run npm start
.
-
Visit http://localhost:4200
From the CLI
-
Install phantomjs from http://phantomjs.org
-
Run npm test
Release 1.0.0-beta.16 (March 23, 2015)
Breaking Changes
The store now passes snapshots instead of records to adapter methods
In 1.0.0-beta.15 serializers were updated to be passed snapshots instead of
records to prevent side-effects like fetching data when inspecting
relationships. This has now been extended to also include adapters methods.
The following adapter methods are now passed snapshots instead of records:
find(store, type, id, snapshot)
findMany(store, type, ids, snapshots)
findHasMany(store, snapshot, url, relationship)
findBelongsTo(store, snapshot, url, relationship)
createRecord(store, type, snapshot)
updateRecord(store, type, snapshot)
deleteRecord(store, type, snapshot)
The signature of buildURL(type, id, snapshot)
has also been updated to receive
snapshots instead of records.
This change removes the need for adapters to create snapshots manually using the
private API record._createSnapshot()
to be able to pass snapshots to
serializers.
Snapshots are backwards-compatible with records (with deprecation warnings) and
it should be pretty straight forward to update current code to the public
Snapshot API:
post.id => postSnapshot.id
post.title => postSnapshot.attr('title')
post.author => postSnapshot.belongsTo('author')
post.comments => postSnapshot.hasMany('comments')
post.constructor => postSnapshot.type;
post.constructor.typeKey => postSnapshot.typeKey
If you need to access the underlying record of a snapshot you can do so by
accessing snapshot.record
.
The full API reference of DS.Snapshot
can be found here.
Changes
- Do not re-add deleted records to a hasMany relationship
- Shorten the list of reserved attributes on the model
- Remove _createSnapshot() from DS.Snapshot documentation examples
- Pass snapshots to adapters instead of records
- Refactor the model assert so it will be correctly removed from the prod build.
- Adapters and Serializers are Store Managed
- Delete
Ember.required
(it is deprecated). - Adding clearer wording for calling super form extract messages
- Missing parameter for JSDoc
- Add examples of how to use model.errors in a template
- Add doc example for defaultValue as a function on DS.attr
- Update the InvalidError docs to make it more clear about where the server payload gets normalized.
- Assert if the user tries to redefine a reserved property name.
- Remove container deprecation warnings in Ember Data tests
- hasRecordForId should return false if the record is not loaded
- [BUGFIX] fetching an empty record runs find
- bump ember-cli to 2.0 & remove sourcemapping comments in production
- commit record-arrays.js separately so it doesn't clobber the rename
- Rename local files to use dashes instead of underscores
- Have snapshots respect the order of items in hasMany relationships
- remove ManyArray from record_arrays
- update docs about
store
in serializer - fetch() -> fetchById() in docs
- Run findHasMany inside an ED runloop
- Cleanup debug adapter test: Watching Records
- Fixed didDelete event/callback not fired in uncommitted state
- Add main entry point for package.json.
- register the store as a service
- Warn when expected coalesced records are not found in the response
- Warn if calling attr, belongsTo or hasMany on model
- move Model to use default export instead of named export
- Move buildURL and related methods to a mixin
- Correct modelFor model not found errors
- Declare
store
property on DS.Model - improve error message for belongsTo
- Move _adapterRun onto the DS.Store object
- Move utility functions out of DS.Store, and into their own modules for reuse across ember-data
- CLean up implicit relationships on record unload
- Add assertion for
store
property on DS.Model subclasses - Adds support for using mixins in polymorphic relationships
- [DOC]: Clarify when didCreate is fired
- (Docs) ManyArray is no longer a RecordArray
- Fix: root.deleted.invalid state