Models — Defining Record Shapes

app/models/post.js Extends Model

Models — Defining Record Shapes

A model file lists attributes and relationships, and Ember Data builds typed records with dirty tracking from it.

4 min read Level 2/5 #ember#ember-data#models
What you'll learn
  • Generate a model with the ember-cli generator
  • Extend from the ember-data Model base class
  • Type fields with the attr decorator

A model declares the schema for one resource type. The CLI scaffolds it, then you fill in attributes and relationships.

Generate

ember generate model post title:string published:boolean

This creates app/models/post.js:

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

export default class PostModel extends Model {
  @attr('string') title;
  @attr('boolean') published;
}

What You Get

For every record you can:

  • Read attrs as plain getters — post.title
  • Write them — post.title = 'New'
  • Check dirtiness — post.hasDirtyAttributes
  • Save — await post.save()
  • Delete — await post.destroyRecord()

TypeScript Augmentation

If you use TypeScript, Ember Data registers types in a global map. Add yours:

declare module 'ember-data/types/registries/model' {
  export default interface ModelRegistry {
    post: PostModel;
  }
}

Now this.store.findRecord('post', id) is typed as Promise<PostModel>.

Where Models Live

Every model file lives at app/models/<kebab-case-name>.js. The filename matches the type string you pass to the store — post.js'post'.

Attributes & Transforms →