Commits

Kenneth Jørgensen committed 60539ee

Added complaints when saving models with unsved references

  • Participants
  • Parent commits 5b48164

Comments (0)

Files changed (3)

File spec/ModelSpec.coffee

 				expect(call.args[0]).toBe model
 
 	describe "relations", ->
-		class ForeignModel extends Model
 		class RelationalModel extends Model
 			persistor: TestPersistor
 			relations:
 				foo:
-					model: ForeignModel
+					model: Model
 				bar:
 					collection: Collection
-					model: ForeignModel
+					model: Model
 		model = null
 		foo = null
 		bar = [null,null,null]
 		beforeEach ->
-			foo = new ForeignModel
+			foo = new Model
 			foo.id "foo"
-			bar[0] = new ForeignModel
-			bar[1] = new ForeignModel
-			bar[2] = new ForeignModel
+			bar[0] = new Model
+			bar[1] = new Model
+			bar[2] = new Model
 			bar[0].id "bar:0"
 			bar[1].id "bar:1"
 			bar[2].id "bar:2"
 				expect(collection.get 0).toBe bar[0]
 				expect(collection.get 1).toBe bar[1]
 				expect(collection.get 2).toBe bar[2]
+
+#		it "should complain if model relations do not have an ID when saving", ->
+#			done = sinon.spy()
+#			model.set "foo", new Model
+#			model.save done
+#			waitsFor (-> done.called), "Done never called", 100
+#			runs ->
+#				err = done.getCall(0).args[0]
+#				expect(err.message).toBe "Relation \"foo\" does not have an ID when saving model"
+
+		it "should complain if collection relation entries do not have an ID when saving", ->
+			done = sinon.spy()
+			model.get("bar").add new Model
+			model.save done
+#			waitsFor (-> done.called), "Done never called", 100
+			#runs ->
+			#	err = done.getCall(0).args[0]
+			#	expect(err.message).toBe "Entry in collection relation \"bar\" does not have an ID when saving model"

File spec/TestPersistor.coffee

 		unless _db[id]?
 			_.defer -> callback new Error "not-found"
 			return
-		_.defer => callback null, _db[id]
+		if _.isFunction callback
+			_.defer => callback null, _db[id]
 
 	save: (model, callback) ->
 		id = model.id()
 		_db[id] = model
-		_.defer -> callback null
+		if _.isFunction callback
+			_.defer -> callback null

File src/Model.coffee

 		return @_persistor
 
 	# Saves the model through the defined persistor.
-	save: (callback) ->
+	save: (done) ->
 		persistor = @getPersistor()
-		persistor.save @, callback
+		# Check relations for IDs. We can't save ID references unless all relations were previously saved.
+		for own field, relation of @relations
+			val = @get field
+			continue if _.isEmpty val
+			if relation.collection?
+				val.each (entry) ->
+					do (entry) -> _.defer -> done new Error "Entry in collection relation \"#{field}\" does not have an ID when saving model" unless entry.id()?
+			else
+				do (val) -> _.defer -> done new Error "Relation \"#{field}\" does not have an ID when saving model" unless val.id()?
+		# Execute save.
+		persistor.save @, done
 		return @
 
 	# Fetches all the defined relations.