22

When I define an attribute for a model in ember-data, can I specify a default value?

The ember-data model definition suggests attributes are defined like this:

attributeName: DS.attr('number')

...with an optional second argument as an options hash. I've looked at the code but my code-reading skills aren't up to figuring out what attributes I can put in the options hash. Is it possible to do something like this?

attributeName: DS.attr('number', { default: 0 })

or

attributeName: DS.attr('boolean', { default: false })

?

pjmorse
  • 9,204
  • 9
  • 54
  • 124

2 Answers2

32

You were close, it's defaultValue, see attributes.js#L63-65.

pangratz
  • 15,875
  • 7
  • 50
  • 75
  • 1
    Brilliant. I realized it couldn't be "default" because that's a JS reserved word. – pjmorse Jun 05 '12 at 00:10
  • 1
    Technically, it still could be "default", you'd just have to put it in quotes. – musicnothing May 07 '15 at 21:55
  • Would recommend linking to the usage guide and add the example into the answer :). https://guides.emberjs.com/release/models/defining-models/#toc_options and @attr('boolean', { defaultValue: false }) verified; – devonbleibtrey May 26 '21 at 19:55
4

defaultValue doesn't work if the property is null. It only works for 'undefined' attributes. See this

iOS dev
  • 470
  • 7
  • 23