Attributes and Transforms

attr("type") — string, number, boolean, date, or Custom

Attributes and Transforms

The attr decorator declares a primitive on a model. Pass a type string for a built-in transform or register a custom one.

4 min read Level 2/5 #ember#ember-data#attributes
What you'll learn
  • Use the built-in attr types (string, number, boolean, date)
  • Set defaults via the attr options
  • Write a custom transform

@attr declares one field on a model. The string you pass picks a transform — the bit of code that converts the raw JSON value into a typed JS value and back.

Built-In Types

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

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

Internally there are four built-in transforms: string, number, boolean, and date. The date transform parses ISO-8601 into a Date.

Defaults

Pass options as the second arg:

@attr('string',  { defaultValue: 'untitled' }) title;
@attr('boolean', { defaultValue: false })       published;
@attr('date',    { defaultValue: () => new Date() }) createdAt;

Use a function form when the default is non-primitive — otherwise every new record would share the same reference.

Custom Transforms

Need a decimal, a money type, or a tagged enum? Register a transform at app/transforms/decimal.js:

import Transform from '@ember-data/serializer/transform';

export default class DecimalTransform extends Transform {
  deserialize(serialized) {
    return serialized == null ? null : Number(serialized);
  }
  serialize(value) {
    return value == null ? null : String(value);
  }
}

Use it just like any built-in:

@attr('decimal') price;

No Type? No Transform.

@attr with no type passes the raw value through. Handy for free-form JSON fields, but you lose normalization.

Relationships →