WhilseySoon
WhilseySoon

Reputation: 322

EmberJS doesn't populate camelCased attributes

EmberJS doesn't populate model attributes written in camelCase for some reason. I use JSONAPIAdapter (RESTAdapter is not an option). Here is my model:

import DS from 'ember-data';
export default DS.Model.extend({
    shortName: DS.attr('string'),
    fullName: DS.attr('string'),
    inn: DS.attr('string'),
    kpp: DS.attr('string'),
    checkingAccount: DS.attr('string'),
    correspodentAccount: DS.attr('string'),
    bik: DS.attr('string'),
});

My handlebars template:

{{#each model as |company|}}
        <tr class="companies-list__item">
            <td class="companies-list__property">{{company.shortName}}</td>
            <td class="companies-list__property">{{company.inn}}</td>
            <td class="companies-list__property">{{company.kpp}}</td>
            <td class="companies-list__property">{{company.checkingAccount}}</td>
            <td class="companies-list__property">{{company.correspodentAccount}}</td>
            <td class="companies-list__property">{{company.bik}}</td>
        </tr>
{{/each}}

Answer from server looks like this:

{
   type: 'company',
   id: 4,
   attributes: {
          shortName: 'Рога и копыта',
          fullName: 'ООО Рога и копыта',
          inn: '312312312',
          kpp: '767675572',
          checkingAccount: '3123145124',
          correspodentAccount: '6547598',
          bik: '76979356'
   },
 },

It does populate inn, kpp, bik, but doesn't use others. What's the problem?

Upvotes: 1

Views: 242

Answers (2)

michael villander
michael villander

Reputation: 26

Ember.js relies on naming conventions, and it expects that multiple-word-camel-case (e.g. firstName) model properties to be mapped to multiple-word-underscore-separated-lower-case attributes (e.g. first_name) on the JSON response. If your JSON is giving you firstName, or anything that is not in this convention in a scenario that you do not control the backend API, you have the option of defining a map which tells your adapter to look for a specific key in the JSON response and map it to a property in a given Model.

You can do something like this:

DS.RESTAdapter.map('App.User', { 
    shortName: { key: 'shortName' },
    fullName: { key: 'fullName' }
});

Upvotes: 1

pixelhandler
pixelhandler

Reputation: 625

When using the JSONAPIAdapter/Serializer, I think that the default for attributes in the JSON payload is dasherized (kabob-case). See https://guides.emberjs.com/v2.10.0/models/customizing-serializers/ you may need to make some customizations.

Upvotes: 4

Related Questions