Mitya
Mitya

Reputation: 1023

How to write Ruby on Rails validations dependant on multiple attributes of a class?

Let's say I have a model class with 3 attributes. I'd like to make sure that at least one of the three is present.

Do I have to write a custom validation for this? Or is there a way to do this with an existing validation helper?

Upvotes: 2

Views: 644

Answers (2)

McStretch
McStretch

Reputation: 20645

A custom validation in your model would be the cleanest way in my opinion:

class Model
  validate :at_least_one_present

  def at_least_one_present
    if(they_dont_exist)
      errors.add("need at least one of these fields")
    end
  end
end

Reference: Creating custom validation methods

Upvotes: 2

thefugal
thefugal

Reputation: 1214

You will need to write a custom validator for this. All you need to do is subclass ActiveModel::Validator and implement a validate(record) method, which adds to the record's errors hash in the event of an error:

class YourValidator < ActiveModel::Validator
    def validate(record)
        if (your_failure_condition_here)
            record.errors[:base] << "Your error message"
        end
    end
end

And then use the validator in your model like so (assuming you've appropriately loaded your validator class):

class YourModel
    validates_with YourValidator
end

Upvotes: 3

Related Questions