Skip to content
Browse files

In `findRelated, remove ids for unchanged models on a relation from `…

…keyId(s)`.
  • Loading branch information...
1 parent 0b1c879 commit 68bf90f4a46cf9470c2be4b5d44cce8e80508f37 @PaulUithol committed Mar 27, 2013
Showing with 26 additions and 3 deletions.
  1. +8 −0 backbone-relational.js
  2. +18 −3 test/tests.js
View
8 backbone-relational.js
@@ -696,6 +696,11 @@
related = this.relatedModel.findOrCreate( this.keyContents, opts );
}
+ // Nullify `keyId` if we have a related model; in case it was already part of the relation
+ if ( this.related ) {
+ this.keyId = null;
+ }
+
return related;
},
@@ -906,6 +911,9 @@
related.set( toAdd, _.defaults( { merge: false, parse: false }, options ) );
}
+ // Remove entries from `keyIds` that were already part of the relation (and are thus 'unchanged')
+ this.keyIds = _.difference( this.keyIds, _.pluck( related.models, 'id' ) );
+
return related;
},
View
21 test/tests.js
@@ -1047,12 +1047,23 @@ $(document).ready(function() {
agentJSON = agent.toJSON();
equal( agentJSON.customers.length, 2, "2 customers in agentJSON; `idAttribute` for 1 missing, other existing" );
- c1.destroy();
+ //c1.destroy();
+
+ //agentJSON = agent.toJSON();
+ //equal( agentJSON.customers.length, 1, "1 customer in agentJSON; `idAttribute` for 1 missing, other destroyed" );
+
+ agent.set( 'customers', [ 'c1', 'c3' ] );
+ var c3 = new Customer( { id: 'c3' } );
+
+ agentJSON = agent.toJSON();
+ equal( agentJSON.customers.length, 2, "2 customers in agentJSON; 'c1' already existed, 'c3' created" );
+
+ agent.get( 'customers' ).remove( c1 );
agentJSON = agent.toJSON();
- equal( agentJSON.customers.length, 1, "1 customer in agentJSON; `idAttribute` for 1 missing, other destroyed" );
+ equal( agentJSON.customers.length, 1, "1 customer in agentJSON; 'c1' removed, 'c3' still in there" );
- // Person -> User; `idAttribute` on a HasMany
+ // Person -> User; `idAttribute` on a HasOne
var person = new Person({ id: 'p1', user: 'u1' } ),
personJSON = person.toJSON();
@@ -1063,6 +1074,10 @@ $(document).ready(function() {
ok( u1.get( 'person' ) === person );
equal( personJSON.user_id, 'u1', "`user_id` gets set in JSON" );
+ person.set( 'user', 'u1' );
+ personJSON = person.toJSON();
+ equal( personJSON.user_id, 'u1', "`user_id` gets set in JSON" );
+
u1.destroy();
personJSON = person.toJSON();
ok( !u1.get( 'person' ) );

0 comments on commit 68bf90f

Please sign in to comment.
Something went wrong with that request. Please try again.