jribeiro
jribeiro

Reputation: 3463

Ember Data - Assign a value inside an object

I'm starting up with ember and trying to get some data from an Api and assign it to an Emberjs model.

My api returns something like:

    [
    {
        email: '[email protected]'
        name: {
            firstname: 'first name',
            lastname: 'last name'
        }
    }
    {
        email: '[email protected]'
        name: {
            firstname: 'another first name',
            lastname: 'another last name'
        }
    },
    {
        email: '[email protected]'
        name: undefined
    }

]

And my code is:

App.Store = DS.Store.extend({
  revision: 12,
});

App.Store.registerAdapter('App.Users', DS.Adapter.extend({
  findAll: function(store, type, id) {
    $.getJSON('https://domain.com/users?callback=?', {
        'auth_token': token
    }).done(function(json){
        store.loadMany(type, json);
    });
  },
}));

App.Store.registerAdapter('App.Users', DS.Adapter.extend({
  findAll: function(store, type, id) {
    $.getJSON('https://domain.com/users?callback=?', {
        'auth_token': token
    }).done(function(json){
        store.loadMany(type, json);
    });
  },
}));

App.Router.map(function() {
    this.route("users", { path: "/users" });
});

App.UsersRoute = Ember.Route.extend({
  model: function() {
    return App.Users.find();
  }
});

App.Users = DS.Model.extend({
    email: DS.attr('string'),
    firstname: DS.attr('string'),
    didLoad: function() {
        console.log('model loaded', this.toJSON());
    }
});


 <script type="text/x-handlebars" data-template-name="users">
    {{#each model}}
        {{email}} - {{firstname}}
    {{/each}}
</script>

Obviously firstname is empty for every object in the array.

Does anyone know what's the proper way to do this?

Thanks

Upvotes: 0

Views: 169

Answers (1)

intuitivepixel
intuitivepixel

Reputation: 23322

Have you tried setting up your User model like this:

App.Adapter.map('App.User', {
  name: {embedded: 'always'}
});

App.User = DS.Model.extend({
  email: DS.attr('string'),
  name: DS.belongsTo('App.UserName')
});

App.UserName = DS.Model.extend({
  firstName: DS.attr('string'),
  lastName: DS.attr('string')
});

Upvotes: 1

Related Questions