So I am doing a chat application (frontend in ember.js and backend in django) which of course has to send messages.
My message model in ember.js looks like this:
Messages.Message = DS.Model.extend({
body: attr('string'),
user: DS.belongsTo('user'),
time: attr('date'),
recipient: DS.belongsTo('recipient'),
});
I tried to create and persist new message using code from this example: http://emberjs.com/guides/models/creating-and-deleting-records/
so my saveMessage action in controller looks like this:
var store = this.store;
var message = store.createRecord('message', {
body: 'Lorem ipsum'
});
store.find('recipient', 2).then(function(recipient) {
message.set('recipient', recipient);
});
message.save();
but the generated JSON`s attribute 'recipient' is null, so server returns error 500 because this field cannot by blank.
JSON should looks like:
{'body': 'loremipsum', 'recipient': {'username','some name'}, 'time': null, 'user': null}
Do you have an idea how to do this?
find
is asynchronous, and returns a promise. That means the anonymous function passed to the then
can likely be executed after you've called save
. Move the save inside the then so that the recipient has been attached before saving.
var store = this.store;
var message = store.createRecord('message', {
body: 'Lorem ipsum'
});
store.find('recipient', 2).then(function(recipient) {
message.set('recipient', recipient);
message.save();
});