Skip to content
Tutorials Center
My learning

Topics

Lesson 17 of 39 ยท Ember Data and Models

Models, Attributes and Transforms

Define Ember Data models with @attr, default values, built-in and custom transforms and derived getters, and see how attributes are converted - with runnable stand-ins.

A model describes what a record is: which fields it has and what type each one is. Good models make the rest of the app simpler, because templates, forms and tests can rely on stable, typed fields. This lesson covers attributes, defaults, transforms (type conversion between the server and your code) and derived properties.

Real versus stand-in. Model code is real Ember Data, read-only here. The runnable blocks reproduce transforms and defaults in plain JavaScript so you can see the conversions.

Declaring attributes

JavaScript
// app/models/product.js
import Model, { attr } from '@ember-data/model';

export default class ProductModel extends Model {
  @attr('string') name;
  @attr('number') priceCents;
  @attr('boolean', { defaultValue: true }) isActive;
  @attr('date') createdAt;
  @attr tags;
}
  • @attr('string') names the transform used to convert the value. Built in: string, number, boolean, date.
  • @attr with no type leaves the value untouched, which suits arrays and objects.
  • defaultValue gives new records a starting value. For mutable values use a function: @attr({ defaultValue: () => [] }) tags; so records do not share one array.
  • Attribute names use camelCase in JavaScript; the serializer converts to the server's naming (price-cents in JSON:API by default).

Generate with the CLI: ember generate model product name:string price-cents:number is-active:boolean.

What transforms do

Servers speak JSON, which has strings, numbers, booleans, null, arrays and objects. Your app wants dates, money, enums. A transform has two directions:

  • deserialize: from the server's JSON value to your JavaScript value (on load).
  • serialize: from your JavaScript value to JSON (on save).
JS Stand-in: transforms in both directions

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

No output.

Custom transforms

If your API stores money as a string like "12.99" and you want cents as a number, write a transform:

JavaScript
// app/transforms/cents.js
import Transform from '@ember-data/serializer/transform';

export default class CentsTransform extends Transform {
  deserialize(serialized) {
    return serialized == null ? null : Math.round(parseFloat(serialized) * 100);
  }

  serialize(deserialized) {
    return deserialized == null ? null : (deserialized / 100).toFixed(2);
  }
}

Use it by file name: @attr('cents') price;. Other common custom transforms: enumerations, comma-separated lists to arrays, and wrapping values in value objects such as a Money or Duration class.

JS A custom transform

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

No output.

Derived properties

Anything you can compute from attributes should be a getter, not a stored field. Records are tracked, so a getter that reads attributes updates automatically:

JavaScript
export default class ProductModel extends Model {
  @attr('string') name;
  @attr('number') priceCents;
  @attr('number', { defaultValue: 0 }) discountPercent;

  get finalPriceCents() {
    return Math.round(this.priceCents * (1 - this.discountPercent / 100));
  }

  get displayPrice() {
    return `$${(this.finalPriceCents / 100).toFixed(2)}`;
  }

  get isOnSale() {
    return this.discountPercent > 0;
  }
}
JavaScript
<template>
  <h2>{{@model.name}} {{#if @model.isOnSale}}<span class="badge">Sale</span>{{/if}}</h2>
  <p>{{@model.displayPrice}}</p>
</template>

Because getters on a model are not sent to the server (only @attr fields are), they are the right place for display logic such as full names, formatted prices, status labels and validation flags. If a getter is expensive, see Derived State: Getters and @cached.

JS Stand-in: a model with defaults and getters

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

No output.

Tracking changes

Ember Data remembers the last saved value of each attribute:

JavaScript
const product = await this.store.findRecord('product', 1);
product.name = 'Large Mug';

product.hasDirtyAttributes;   // true
product.changedAttributes();  // { name: ['Mug', 'Large Mug'] }
product.rollbackAttributes(); // back to 'Mug'

changedAttributes() returns [oldValue, newValue] pairs, perfect for "you changed 2 fields" summaries or a diff before saving. rollbackAttributes() throws away unsaved edits, which is exactly what a Cancel button should call. The full save flow is in Creating, Updating and Deleting Records.

Naming conventions

Thing Convention Example
Model file singular, dasherized app/models/blog-post.js
Model name in the store same, singular findRecord('blog-post', 1)
Attribute in JS camelCase publishedAt
Attribute in JSON:API dasherized published-at
Resource type in JSON:API plural, dasherized blog-posts

Common mistakes

  • A shared default array or object. defaultValue: [] is shared by all records; use a function.
  • Storing derived values as attributes. They get out of sync and are sent to the server; write a getter.
  • Expecting getters to be saved. Only @attr fields (and relationships) are serialized.
  • Mixing up transform names. @attr('int') does not exist; use number.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does a transform's serialize method do?

    deserialize runs on load, serialize runs on save. The two are inverses.
  2. 2. Why write defaultValue as a function for an array attribute?

    A plain array literal would be one shared object across all records.
  3. 3. Where should a formatted price for display live?

    Derived display values are getters; they update when attributes change and are not sent to the server.
  4. 4. What does rollbackAttributes() do?

    It restores the last loaded or saved values, which is what a Cancel button needs.

Summary

  • Declare fields with @attr('type'); built-in transforms are string, number, boolean and date.
  • Write custom transforms with deserialize and serialize for money, enums or lists.
  • Use function defaults for arrays and objects.
  • Put derived values in getters; they are tracked and never serialized.
  • hasDirtyAttributes, changedAttributes() and rollbackAttributes() manage unsaved edits.

Next: Relationships: belongsTo and hasMany