Raising an error when adding an un-saved item to a collection
This commit is contained in:
parent
1a551b54eb
commit
796f7d9f7e
2 changed files with 20 additions and 5 deletions
|
@ -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
|
||||
|
||||
|
||||
|
|
|
@ -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
|
||||
end
|
||||
|
|
Loading…
Reference in a new issue