Undistraction
Undistraction

Reputation: 43579

Validate Presence Of At Least One of Several

I have an ActiveRecord model with the following three attributes:

data_1
data_2
data_3

How do I write a validation that checks whether at least one of those fields is not blank?

Upvotes: 2

Views: 1807

Answers (3)

MegaTux
MegaTux

Reputation: 1651

You can play with the list of attributes and the collection #any? #all? methods:

[attr1, attr2, ..., attrN].all? {|a| a.nil? || a == "" }

[attr1, attr2, ..., attrN].map(&:to_s).any? {|a| !a.empty? }

This is plain Ruby, ActiveSupport it's even easier, you have #present? or #blank?, e.g.:

[attr1, attr2, ..., attrN].any?(&:present?)

Last, for two values you can use XOR operation: value1 ^ value2

Upvotes: 0

maximus ツ
maximus ツ

Reputation: 8065

This can be done with custom validator like this,

in your model write,

 validates :validate_attrlist

 def validate_attrlist
    unless !data_1.blank? or !data_2.blank? or !data_3.blank?
       record.errors[:base] << "Can't be blank"
    end
  end

Upvotes: 4

Undistraction
Undistraction

Reputation: 43579

Ok. Here is how I did it

validate :has_content


def has_content
  if data_1.blank? && data_2.blank? && data_3.blank?
    errors[:base] = "Must have a filename or a URL"
  end
end

Upvotes: 1

Related Questions