简体   繁体   中英

active record validations - mutually exclusive attributes

I want to validate attributes in my model such that if one is present other should not be. Suppose there are 2 attributes -

if a present:
  b should be NULL
  c should be NULL

How can I use validates to do this?

:validates a, b => NULL, c => NULL

You can use a custom validation:

validate :check_presence

def check_presence
  if !self.a.blank?
    if !self.b.blank? or !self.c.blank?
      errors[:base] << " b and c should be null."
    end
  end
end

I find it quite readable to use :absence with if: like so :

validates :b, :absence, if: :a
validates :c, :absence, if: :a

Or if you also want complete mutual exclusiveness for a , b and c :

validates :a, :absence, if: ->(r) { r.b || r.c }
validates :b, :absence, if: ->(r) { r.a || r.c }
validates :c, :absence, if: ->(r) { r.a || r.b }

Or using a method:

validate :ensure_mutual_exclusion

def ensure_mutual_exclusion
  errors.add(:base, "...") if [a, b, c].count(&:present?) > 1
end

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM