简体   繁体   中英

Creating record with belongsTo relationship error - Ember.js

Given the two models: Message.js and User.js, I keep getting the following error when trying to create a record with Ember.js. Any Ember.js wizards know what could be wrong with my code?

// Error: Assertion Failed: You can only add a 'user' record to this relationship

App.Message = DS.Model.extend({
 title: DS.attr(),
 body: DS.attr(),
 user: DS.belongsTo('user'),
});

App.User = DS.Model.extend({
  first_name: DS.attr(),
  last_name: DS.attr(),
  email: DS.attr(),
  password: DS.attr(),
  messages: DS.hasMany('message'),
});


App.NewMessageController = Ember.Controller.extend({
need: ['application'],
thisUserID: Ember.computed.alias('controllers.application.userID'),

actions: {
    save: function() {
        // Prints -> 'thisUserID' -- all is fine here
        console.log('The user id from new-letter is: '+this.get('thisUserID')); 

        var store = this.store;
        //Prints -> <DS.PromiseObject:ember433> -- Strange?
        console.log("Checking the store: "+store.find('user', this.get('thisUserID'))); 

        var newMessage = store.createRecord('message', {
            title: this.get('title'),
            body: this.get('body'),
        });
        newMessage.save();

        // Prints-> Error: Assertion Failed: You can only add a 'user' record to this relationship
        var user = store.find('user', this.get('thisUserID')).then(function(user) {
          newMessage.set('user', user);
        });
    }
}
});

I'm not a wizard, but it seems that you're trying to set the user record to a message: newMessage.set('user', user);

Instead, you should add the message: user.get('messages').addObject(newMessage);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM