Reputation: 8176
I have a dialer that points to a person:
App.Dialer = DS.Model.extend({
created_at: DS.attr('date'),
person: DS.belongsTo('App.Person'),
didCreate: function() { alert('didCreate: ' + this + ', ' + this.get('person')); }
});
App.Person = DS.Model.extend({
name: DS.attr('string'),
dialers: DS.hasMany('App.Dialer')
});
I create a new dialer:
var d = App.store.createRecord(App.Dialer, {
person: App.Person.find(1)
});
alert('before commit: ' + d + ', ' + d.get('person'));
App.store.commit();
alert('after commit: ' + d + ', ' + d.get('person'));
It creates the record correctly on the server, with person_id set correctly. The two alert statements before and after calling commit() also work correctly, with both the dialer object and it's person object being populated.
However, after the record is created, when Ember calls my didCreate event handler, the person association has disappeared, and instead I get 'null' when I call this.get('person'), even though the value of 'this' is the new dialer object, with the same id as the first two alerts.
Upvotes: 1
Views: 329
Reputation: 1528
For Update (PUT)
I've found that HTTP server responses of 204 No Content
(with an empty body) avoid resetting associations during a multi-request commit.
Historically I prefer REST API's to return 200 OK
with the updated data, but this is a sensible alternative to avoid polluting the client-side data midway through a commit.
For Create (POST)
On your Dialer model, compose a callback to reload the object after the transaction completes:
didCreate: function() {
// Re-GET the backing data to populate associations that were wiped out during nested creation.
Ember.run.next(this, function() {
this.get('store').findQuery(App.Dialer, { ids: [this.get('id')] });
});
}
It causes an additional HTTP request, and will also probably require server changes to return the object for the query. For my Rails 3.2 app, I made a controller action like:
def index
if Array===params[:ids]
@dialers = Dialer.find(params[:ids])
else
@dialers = []
end
render :index
end
Upvotes: 1