I’m trying to set a boolean field to false based on the value of another boolean field. I tried the following with an ActiveRecord model:
before_save :reconcile_xvent
def reconcile_xvent
self.xvent_hood = false if !self.xvent_plenum?
end
But this doesn’t work. Now, many of my unit tests fail with:
ActiveRecord::RecordNotSaved: ActiveRecord::RecordNotSaved
How can I set xvent_hood to be false if xvent_plenum is false?
Update
Here’s what works (some of which comes from the comments/answers below):
before_validation :reconcile_xvent
def reconcile_xvent
if self.xvent_hood?
self.xvent_hood = false unless xvent_plenum?
end
end
I couldn’t figure out to make it work without the “if self.xvent_hood?” part….
before_saveis only called after validation has passed. What you need to do is movereconcile_xventup tobefore_validationrather thanbefore_saveIf you keep that method in
before_savewhat will happen is that it thinks thatxvent_hoodis null, if you have a validation that checks for nullity ofxvent_hoodit will fail before thebefore_savegets called. Which probably explains why you gotRecordNotSavederror.Another thing to keep in mind is that if you have a boolean property, you also can’t use
validate_presence_of. See http://alexanderwong.me/post/16084280769/rails-validate-presence-of-boolean-and-arrays-mongoid