Search code examples
ember.jsember-dataember-cli

How can I add default values for ember has many relationship?


I'm using Ember 2.5.0 and I have two models service and availability which looks like:

// availability
import DS from 'ember-data';

export default DS.Model.extend({
  day: DS.attr('string'),
  enabled: DS.attr('boolean'),
  startAt: DS.attr('string'),
  endAt: DS.attr('string'),
  service: DS.belongsTo('service')
});

And service which looks like:

import DS from 'ember-data';

export default DS.Model.extend({
  name: DS.attr('string'),
  description: DS.attr('string'),
  availabilities: DS.hasMany('availability',
    {
      defaultValue:
        [
          {
            day: 'saturday',
            enabled: false,
            startAt: '',
            endAt: ''
          },
          {
            day: 'sunday',
            enabled: false,
            startAt: '',
            endAt: ''
          }
        ]
    }
  )
});

As you can see I was trying to use defaultValue but with no luck. For new route I want to set default values if we are creating a new service record.

Any help is appreciated.


Solution

  • The argument hash that DS.hasMany only accepts two properties: async and inverse. It doesn't accept a defaultValue property though. (source).

    But fear not, Eki Eqbal! I think you can accomplish something similar by using your model's ready() hook.

    import DS from 'ember-data';
    
    export default DS.Model.extend({
      name: DS.attr('string'),
      description: DS.attr('string'),
      availabilities: DS.hasMany('availability', { async: true }), // is the data loaded async?
    
      ready() { // fires when the model is loaded from server or created locally
        if (!!this.get('availabilities')) {
          // don't set to defaults if availabilities is not null
          return;
        }
    
        var saturday = this.store.createRecord('availability', {
          day     : 'saturday',
          enabled : false,
          startAt : '',
          endAt   : ''
        });
    
        var sunday = this.store.createRecord('availability', {
          day     : 'sunday',
          enabled : false,
          startAt : '',
          endAt   : ''
        });
    
        this.get('availabilities').pushObjects([saturday, sunday]);
      }
    });