user2851669
user2851669

Reputation:

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

Upvotes: 1

Views: 562

Answers (2)

François F
François F

Reputation: 144

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

Upvotes: 0

Shannon
Shannon

Reputation: 3018

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

Upvotes: 2

Related Questions