Raising an error when adding an un-saved item to a collection

This commit is contained in:
Sam Lown 2010-08-04 11:54:02 +02:00
parent 1a551b54eb
commit 796f7d9f7e
2 changed files with 20 additions and 5 deletions

View file

@ -171,27 +171,32 @@ module CouchRest
(array ||= []).compact! (array ||= []).compact!
casted_by[property.to_s] = [] # replace the original array! casted_by[property.to_s] = [] # replace the original array!
array.compact.each do |obj| array.compact.each do |obj|
check_obj(obj)
casted_by[property.to_s] << obj.id casted_by[property.to_s] << obj.id
end end
super(array) super(array)
end end
def << obj def << obj
check_obj(obj)
casted_by[property.to_s] << obj.id casted_by[property.to_s] << obj.id
super(obj) super(obj)
end end
def push(obj) def push(obj)
check_obj(obj)
casted_by[property.to_s].push obj.id casted_by[property.to_s].push obj.id
super(obj) super(obj)
end end
def unshift(obj) def unshift(obj)
check_obj(obj)
casted_by[property.to_s].unshift obj.id casted_by[property.to_s].unshift obj.id
super(obj) super(obj)
end end
def []= index, obj def []= index, obj
check_obj(obj)
casted_by[property.to_s][index] = obj.id casted_by[property.to_s][index] = obj.id
super(index, obj) super(index, obj)
end end
@ -205,6 +210,13 @@ module CouchRest
casted_by[property.to_s].shift casted_by[property.to_s].shift
super super
end 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 end

View file

@ -178,12 +178,15 @@ describe "Assocations" do
@invoice.entry_ids.first.should eql(@entries[1].id) @invoice.entry_ids.first.should eql(@entries[1].id)
end 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 SaleEntry.find_by_description('test entry').should be_nil
entry = SaleEntry.new(:description => 'test entry', :price => 500) entry = SaleEntry.new(:description => 'test entry', :price => 500)
lambda {
@invoice.entries << entry @invoice.entries << entry
@invoice.save.should be_true }.should raise_error
SaleEntry.find_by_description('test entry').should_not be_nil # In the future maybe?
# @invoice.save.should be_true
# SaleEntry.find_by_description('test entry').should_not be_nil
end end
end end