Skip to content

Commit

Permalink
Merge pull request #376 from elasticsales/master
Browse files Browse the repository at this point in the history
Fix for #375 - toJSON should include IDs of unregistered models
  • Loading branch information
PaulUithol committed Oct 29, 2013
2 parents 6645ea3 + 54e5901 commit 6ae1e60
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 2 deletions.
1 change: 1 addition & 0 deletions backbone-relational.js
Original file line number Diff line number Diff line change
Expand Up @@ -1486,6 +1486,7 @@
}
else if ( rel instanceof Backbone.HasOne ) {
value = value || rel.keyId;
if (!value && !_.isObject(rel.keyContents)) value = rel.keyContents || null;
}
}
}
Expand Down
23 changes: 21 additions & 2 deletions test/tests.js
Original file line number Diff line number Diff line change
Expand Up @@ -1064,7 +1064,7 @@ $(document).ready(function() {

var a1 = new Animal( { id: 'a1' } );
zooJSON = zoo.toJSON();
equal( zooJSON.animals.length, 1, "0 animals in zooJSON; it serializes an array of attributes" );
equal( zooJSON.animals.length, 1, "1 animals in zooJSON; it serializes an array of attributes" );

// Agent -> Customer; `idAttribute` on a HasMany
var agent = new Agent({ id: 'a1', customers: [ 'c1', 'c2' ] } ),
Expand Down Expand Up @@ -1113,14 +1113,33 @@ $(document).ready(function() {
u1.destroy();
personJSON = person.toJSON();
ok( !u1.get( 'person' ) );
equal( personJSON.user_id, null, "`user_id` does not get set in JSON anymore" );
equal( personJSON.user_id, 'u1', "`user_id` still gets set in JSON" );

person = new Person({user : new User({ id : 'u2' })})
equal(person.toJSON().user_id, 'u2')
person.set({user : 'unfetched_user_id'})
equal(person.toJSON().user_id, 'unfetched_user_id')
});

test( "`toJSON` should include ids for unregistered models (if `includeInJSON` is `idAttribute`)", function() {

// Person -> User; `idAttribute` on a HasOne
var person = new Person({ id: 'p1', user: 'u1' } ),
personJSON = person.toJSON();

equal( personJSON.user_id, 'u1', "`user_id` gets set in JSON even though no user obj exists" );

var u1 = new User( { id: 'u1' } );
personJSON = person.toJSON();
ok( u1.get( 'person' ) === person );
equal( personJSON.user_id, 'u1', "`user_id` gets set in JSON after matching user obj is created" );

Backbone.Relational.store.unregister(u1);

personJSON = person.toJSON();
equal( personJSON.user_id, 'u1', "`user_id` gets set in JSON after user was unregistered from store" );
});

test( "`parse` gets called through `findOrCreate`", function() {
var parseCalled = 0;
Zoo.prototype.parse = Animal.prototype.parse = function( resp, options ) {
Expand Down

0 comments on commit 6ae1e60

Please sign in to comment.