Rails: How to use before_save to change a field value based on another field?

前端 未结 2 2173
孤独总比滥情好
孤独总比滥情好 2021-02-18 18:47

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 :reconc         


        
2条回答
  •  花落未央
    2021-02-18 19:24

    before_save is only called after validation has passed. What you need to do is move reconcile_xvent up to before_validation rather than before_save

    If you keep that method in before_save what will happen is that it thinks that xvent_hood is null, if you have a validation that checks for nullity of xvent_hood it will fail before the before_save gets called. Which probably explains why you got RecordNotSaved error.

    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

提交回复
热议问题