0

I find a problem is handlebars input set the data. No matter what type of data, the end will be a string. If I use boolean or date, it will have a problem.

import DS from 'ember-data';

export default DS.Model.extend({
  ...
  sex: DS.attr('boolean'),
  createdAt: DS.attr('date'),
  updatedAt: DS.attr('date')
});

I use select to change the sex. http://balinterdi.com/2015/08/29/how-to-do-a-select-dropdown-in-ember-20.html

<select onchange={{action (mut model.sex) value="model.sex"}}>
  {{#each sexGroup as |sexChoice|}}
    <option value={{sexChoice.value}} selected={{eq model.sex sexChoice.value}}>{{sexChoice.name}}</option>
  {{/each}}
</select>

And set the sexGroup in controller:

sexGroup: [
  Ember.Object.create({value: 1, name: "man"}),
  Ember.Object.create({value: 0, name: "woman"})
]

The problem is whatever my select choice man or woman, Ember data will always send the true to server. Because html select value always is string, and Ember Data attr('boolean') get the string will become true.

If I must solve this problem, I have two way:

No.1(Not use boolean, usr string);

No.2(Use parseInt to set value before save), look like:

this.get('model').set('sex', parseInt(this.get('sexValue')));

The date format also have problem: What is the best way to modify the date format when ember-data does serialization?

So I don't know the role of Ember data boolean and date attribute types. Especially in the use of html input and the value always is string.

So there is a good solution to this situation? Or am I just using a string? Thanks.

Community
  • 1
  • 1
JeskTop
  • 481
  • 1
  • 4
  • 20
  • Ember-data offer [DS.Transform](http://emberjs.com/api/data/classes/DS.Transform.html) class and its `serialize()` and `deserialize()` methods that could help you. Implement your own transform object, say `custom-sex` and make your model property be of that type: `sex: DS.attr('custom-sex'),` Everytime request-response will be received/sent, your `serialize()/deserialize()` methods will run. – Pavol Apr 07 '16 at 09:43
  • @Pavol Thanks. I know this class. But if I use `string` can sovle this problem, why I must custom transform? – JeskTop Apr 07 '16 at 10:02

1 Answers1

1

Instead of using model.sex use a computed property with get and set:

sexStr: Ember.computed('model.sex',{
  get(){
    return this.get('model.sex') ? 'male':'female';
  },
  set(key,value){
    this.set('model.sex', value === 'male');
    return value;
  }
})
Patsy Issa
  • 11,113
  • 4
  • 55
  • 74
Henry Vonfire
  • 1,281
  • 10
  • 18