Skip to content
Tutorials Center
My learning

Topics

Lesson 19 of 39 ยท Ember Data and Models

Creating, Updating and Deleting Records

Create, edit and delete Ember Data records with createRecord, save, rollbackAttributes and destroyRecord, handle server errors and show saving states, with a runnable stand-in.

Reading data is half of an application. The other half is changing it: adding a note, renaming a project, deleting a task. Ember Data gives records a small set of methods for this, and because records are tracked, the interface reflects every step (new, saving, saved, error) without extra bookkeeping.

Real versus stand-in. Route, controller and component code is real Ember Data, read-only here. The runnable blocks use a small in-memory stand-in with a fake server so you can follow the state changes of a save.

Create

createRecord makes a new, unsaved record in the store. Nothing is sent to the server until you call save():

JavaScript
// app/routes/notes/new.js
import Route from '@ember/routing/route';
import { service } from '@ember/service';

export default class NotesNewRoute extends Route {
  @service store;

  model() {
    return this.store.createRecord('note', { title: '', body: '' });
  }

  deactivate() {
    const note = this.modelFor(this.routeName);
    if (note.isNew) {
      note.unloadRecord(); // user left without saving; discard the draft
    }
  }
}
JavaScript
// app/controllers/notes/new.js
import Controller from '@ember/controller';
import { action } from '@ember/object';
import { service } from '@ember/service';

export default class NotesNewController extends Controller {
  @service router;

  @action
  async save(event) {
    event.preventDefault();
    await this.model.save();                       // POST /notes
    this.router.transitionTo('notes.show', this.model.id);
  }
}

save() returns a promise. On success the server's response (including the new id) updates the record, and isNew becomes false.

Update

To update, change attributes on a loaded record and call save() again. Ember Data sends PATCH /notes/1 with the changed attributes (the default JSON:API adapter sends the whole record):

JavaScript
@action
async rename(note, newTitle) {
  note.title = newTitle;   // note.hasDirtyAttributes is now true
  await note.save();       // PATCH /notes/1
}

If the user cancels, throw the edits away:

JavaScript
@action
cancel() {
  this.model.rollbackAttributes(); // for a new record this also removes it
  this.router.transitionTo('notes');
}

For a new record rollbackAttributes() unloads it; for a saved record it restores the last saved values.

Delete

JavaScript
@action
async remove(note) {
  await note.destroyRecord();   // DELETE /notes/1, then unloads the record
}

destroyRecord() is deleteRecord() plus save(). If you want two steps (mark, then confirm), use them separately: note.deleteRecord() marks it (isDeleted), await note.save() sends the request, and note.rollbackAttributes() undoes the mark before saving.

The save lifecycle

stateDiagram-v2
  [*] --> new: createRecord
  new --> saving: save()
  saving --> loaded: success
  saving --> error: failure
  error --> saving: save() again
  loaded --> dirty: change an attribute
  dirty --> saving: save()
  dirty --> loaded: rollbackAttributes()
  loaded --> deleted: deleteRecord()
  deleted --> [*]: save() succeeds

Every record moves through these states; the flags isNew, isSaving, hasDirtyAttributes, isError and isDeleted tell you where it is.

JS Stand-in: a record's save lifecycle

Press Run (or Ctrl + Enter) to see the console output here.

No output.

Showing state in templates

Flags are tracked, so templates can react:

JavaScript
<template>
  <form {{on "submit" this.save}}>
    <input value={{@model.title}} {{on "input" this.setTitle}} />
    <button type="submit" disabled={{@model.isSaving}}>
      {{if @model.isSaving "Saving..." "Save"}}
    </button>
    {{#if @model.hasDirtyAttributes}}<span>Unsaved changes</span>{{/if}}
  </form>
</template>

Binding the input directly to the record as above makes the record dirty as soon as the user types, which suits a dedicated edit page. For forms where a Cancel must be free of side effects, see the copy-the-values approach in Forms and Inputs.

Handling server errors

When the server rejects a save with a 422 response and a JSON:API errors array, Ember Data puts the messages on the record:

JSON
{ "errors": [ { "source": { "pointer": "/data/attributes/title" }, "detail": "can't be blank" } ] }
JavaScript
<template>
  {{#each @model.errors.title as |error|}}
    <p class="error">{{error.message}}</p>
  {{/each}}
</template>

record.errors is keyed by attribute (errors.title), isValid becomes false, and the record returns to normal once the attribute changes. Other failures (a 500, a dropped connection) reject the save() promise, so always wrap it in try/catch:

JavaScript
try {
  await this.model.save();
} catch (error) {
  this.message = 'Could not save. Please try again.';
}

Optimistic versus pessimistic updates

By default a save is pessimistic: the record changes locally at once, and the server may then refuse. If it fails, the local value remains until you rollbackAttributes(). For a delete you usually want the opposite order: remove from the list immediately (optimistic) and bring it back on error:

JavaScript
@action
async remove(note) {
  note.deleteRecord();               // disappears from live lists now
  try {
    await note.save();               // confirm with the server
  } catch {
    note.rollbackAttributes();       // it comes back
  }
}

Common mistakes

  • Never calling save(). createRecord and attribute changes only affect the local store.
  • Leaving abandoned new records. A draft left in the store shows up in findAll/peekAll lists; unload or roll it back when the user leaves.
  • Not catching save errors. An unhandled rejection leaves the UI stuck in "Saving...".
  • Using deleteRecord() alone. It does not contact the server; use destroyRecord() or call save() afterwards.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does store.createRecord do?

    createRecord only affects the store. The request happens when you call save().
  2. 2. Which method deletes on the server and removes the record from the store?

    destroyRecord is deleteRecord plus save. unloadRecord only removes the record from the local cache.
  3. 3. How does a user cancel editing of an existing, changed record?

    rollbackAttributes restores the last saved values, and is the right action for a Cancel button.
  4. 4. A server responds 422 with an errors array. Where do the messages appear?

    Ember Data maps validation errors onto record.errors so templates can show them next to the fields.

Summary

  • createRecord creates a local record; save() sends POST for new records and PATCH for changed ones.
  • rollbackAttributes() cancels edits (and discards new records); destroyRecord() deletes.
  • Tracked flags (isNew, isSaving, hasDirtyAttributes, isError) drive the UI.
  • 422 responses populate record.errors; other failures reject the promise, so use try/catch.
  • Clean up abandoned drafts so they do not appear in lists.

Next: Adapters and Serializers