Search code examples
ember.jsember-dataember-cli

Why can't I set the user id?


I have this in one of my routes.

var order = _this.store.createRecord('order');
order.set('product', product);

this.store.find('userProfile', 1).then(function(user) {
  console.log(user.get('id'));
  order.set('user', user);
});

order.save().then(function() {
  _this.transitionTo('products.index');
});

I get this error:

Error: Assertion Failed: Error: The backend rejected the commit because it was invalid: {userId: can't be blank}

And the API payload looks like:

{"order":{"user_id":null,"product_id":"30"}}

It's strange because console.log(user.get('id')); gets the id of the user, which indicates the user should be the right object.

I seems that the user id is not being set. Which means order.set('user', user); is not executing correclty...

My Order model looks like:

import DS from 'ember-data';

export default DS.Model.extend({
  user:    DS.belongsTo('userProfile'),
  product: DS.belongsTo('product')
});

Did I miss something?


Solution

  • The call to this.store.find is asynchronous and returns a promise. This code is calling order.save() immediately after find, so the promise has not yet resolved, and the user record is still null. This is why there is no user_id in the payload.

    The console.log is inside the then handler, which gets executed once the promise has been fulfilled, so you can access the attributes of the user. Make sure that any code that requires the user object happens inside the then handler.

    this.store.find('userProfile', 1).then(function(user) {
      order.set('user', user);
      order.save();
    });