diff --git a/lib/couchrest/model/associations.rb b/lib/couchrest/model/associations.rb index 0f83f3e..889ff5c 100644 --- a/lib/couchrest/model/associations.rb +++ b/lib/couchrest/model/associations.rb @@ -171,27 +171,32 @@ module CouchRest (array ||= []).compact! casted_by[property.to_s] = [] # replace the original array! array.compact.each do |obj| + check_obj(obj) casted_by[property.to_s] << obj.id end super(array) end def << obj + check_obj(obj) casted_by[property.to_s] << obj.id super(obj) end def push(obj) + check_obj(obj) casted_by[property.to_s].push obj.id super(obj) end def unshift(obj) + check_obj(obj) casted_by[property.to_s].unshift obj.id super(obj) end def []= index, obj + check_obj(obj) casted_by[property.to_s][index] = obj.id super(index, obj) end @@ -205,6 +210,13 @@ module CouchRest casted_by[property.to_s].shift super end + + protected + + def check_obj(obj) + raise "Object cannot be added to #{casted_by.class.to_s}##{property.to_s} collection unless saved" if obj.new? + end + end diff --git a/spec/couchrest/assocations_spec.rb b/spec/couchrest/assocations_spec.rb index 21ad658..deef3cb 100644 --- a/spec/couchrest/assocations_spec.rb +++ b/spec/couchrest/assocations_spec.rb @@ -178,16 +178,19 @@ describe "Assocations" do @invoice.entry_ids.first.should eql(@entries[1].id) end - it "should save all entries when invoice is saved" do + it "should raise error when adding un-persisted entries" do SaleEntry.find_by_description('test entry').should be_nil entry = SaleEntry.new(:description => 'test entry', :price => 500) - @invoice.entries << entry - @invoice.save.should be_true - SaleEntry.find_by_description('test entry').should_not be_nil + lambda { + @invoice.entries << entry + }.should raise_error + # In the future maybe? + # @invoice.save.should be_true + # SaleEntry.find_by_description('test entry').should_not be_nil end end end -end \ No newline at end of file +end