Skip to content

Commit

Permalink
(#16) - Add override so serialiser saves hasMany
Browse files Browse the repository at this point in the history
As suggested by @fsmanuel:
#16 (comment)
  • Loading branch information
backspace authored and nolanlawson committed Feb 1, 2016
1 parent 25c3866 commit 3cb2231
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 2 deletions.
18 changes: 17 additions & 1 deletion addon/serializers/pouch.js
Original file line number Diff line number Diff line change
@@ -1,3 +1,19 @@
import DS from 'ember-data';

export default DS.RESTSerializer.extend({});
export default DS.RESTSerializer.extend({
_shouldSerializeHasMany: function() {
return true;
},

// This fixes a failure in Ember Data 1.13 where an empty hasMany
// was saving as undefined rather than [].
serializeHasMany(snapshot, json, relationship) {
this._super.apply(this, arguments);

const key = relationship.key;

if (!json[key]) {
json[key] = [];
}
}
});
3 changes: 2 additions & 1 deletion tests/dummy/app/models/food-item.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,5 +5,6 @@ import DS from 'ember-data';
export default DS.Model.extend({
rev: DS.attr('string'),

name: DS.attr('string')
name: DS.attr('string'),
soup: DS.belongsTo('taco-soup', { async: true })
});
3 changes: 3 additions & 0 deletions tests/dummy/app/serializers/application.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,3 @@
import { Serializer } from 'ember-pouch';

export default Serializer;
30 changes: 30 additions & 0 deletions tests/integration/adapters/pouch-basics-test.js
Original file line number Diff line number Diff line change
Expand Up @@ -114,6 +114,36 @@ test('create a new record', function (assert) {
});
});

test('creating an associated record stores a reference to it in the parent', function (assert) {
assert.expect(1);

var done = assert.async();
Ember.RSVP.Promise.resolve().then(() => {
return this.db().bulkDocs([
{ _id: 'tacoSoup_2_C', data: { flavor: 'al pastor', ingredients: [] } }
]);
}).then(() => {
return this.store().findRecord('taco-soup', 'C');
}).then(tacoSoup => {
var newIngredient = this.store().createRecord('food-item', {
name: 'pineapple',
soup: tacoSoup
});

return newIngredient.save().then(() => tacoSoup.save());
}).then(() => {
this.store().unloadAll();

return this.store().findRecord('taco-soup', 'C');
}).then(tacoSoup => {
return tacoSoup.get('ingredients');
}).then(foundIngredients => {
assert.deepEqual(foundIngredients.mapBy('name'), ['pineapple'],
'should have fully loaded the associated items');
done();
});
});

// This test fails due to a bug in ember data
// (https://github.com/emberjs/data/issues/3736)
// starting with ED v2.0.0-beta.1. It works again with ED v2.1.0.
Expand Down

0 comments on commit 3cb2231

Please sign in to comment.