Abdelkrim Tabet Aoul
Abdelkrim Tabet Aoul

Reputation: 220

Common conditional validation rule for multiple attributes (rails)

I have an ActiveRecord model with attributes attr1, attr2, attr3, attr4...
For example attr3 and 4 having the same fill status, that mean both of them must be present or absent. I already made this with a couple of conditional validation.

validates :attr4, presence: true, if: :condition?
validates :attr4, absence: true, unless: :condition?

def condition?
  attr3 != ""
end

But I'm wondering if there is a more elegant way to implement that rule.

Upvotes: 0

Views: 689

Answers (1)

Moamen Naanou
Moamen Naanou

Reputation: 1713

You can use custom validator:

class SwapValidator < ActiveModel::EachValidator
  def validate_each(record, attribute, value)
    unless value.present? || record.attr3.present?
      record.errors.add(attribute, :invalid)
    end
  end
end

Then in your model use:

validates :attr4, swap: true

Upvotes: 1

Related Questions