ruby - Calling save on a destroyed object returns true, but doesn't save -
getting weird behavior when trying save mongoid object has been destroyed. given class definition:
class foo include mongoid::document end after saving instance, deleting it, unable save again:
foo.count # => 0 f = foo.create # => #<foo _id: 522744a78d46b9b09f000001, > foo.count # => 1 f.destroy # => true foo.count # => 0 f.save # => true # lied - didn't save: foo.count # => 0 # these may relevant: f.persisted? # => false f.destroyed? # => true f.new_record? # => false f.changed? # => false here's failing rspec test expect pass:
describe foo 'should allow saving foo instance after destroying it' expect(foo.count).to eq(0) f = foo.create expect(foo.count).to eq(1) foo.all.destroy expect(foo.count).to eq(0) f.save # => true expect(foo.count).to eq(1) # error - returns 0 end end is expected behavior? use case using singleton object (didn't want make question more complicated mentioning though); foo.instance returns same object destroyed foo.all.destroy gumming things.
model#save
saves changed attributes database atomically, or insert document if new. raise error of validations fail.
after destruction, document not new , there no attributes have changed, save returns without errors. in strict sense seems expected behavior.
you use model#upsert:
performs mongodb
upserton document. if document exists in database, overwritten current attributes of document in memory. if document not exist in database, inserted.
this save document using same id, still frozen? , marked destroyed?. therefore might better clone document suggested insane-36 in comments.
Comments
Post a Comment