Simplifying Rails Validation I have four fields a, b, c, and d.  All of them must be populated if any of them have a value.

So what I want to do is validate that they are all populated, if any of them have a value.  I'm trying to determine the best way to do this.  I think I could do this:

  class User &lt; ActiveRecord::Base
    validates_presence_of :a, :b, :c, :if =&gt; lambda { self.d.present? }
    validates_presence_of :b, :c, :d, :if =&gt; lambda { self.a.present? }
    validates_presence_of :a, :c, :d, :if =&gt; lambda { self.b.present? }
    validates_presence_of :a, :b, :d, :if =&gt; lambda { self.c.present? }
  end
I noticed that you use 'hard' and repeated parts of code. My way to solve this task is to write a custom validation (I try to avoid them but sometimes there no other choice).

I try to place custom validations in a separate file (in config\initializers\ directory).

ActiveRecord::Base.class_eval do
  def self.validates_dependent_fields(*attr_names)
    fields_count = 0
    attr_names.each{ |attribute| fields_count += 1 if record[attribute] }

    validates_each(attr_names) do |record, attribute, value|
      if value &amp;&amp; fields_count &lt; attr_names.length
        record.errors[attribute] &lt;&lt; "Dependent fields can not be empty."
      end
    end

  end
end


Algorithm:


Get the number of not nil fields;
Validate each field (and add error message if the attribute value is not nil and one or more dependent fields are not present).  


Then, in the model:

class SomeModel &lt; ActiveRecord::Base
  validates_dependent_fields :a, :b, :c, :d
end


Note that you can reuse this validation in any other model.

P.S.: I've not tested this code yet.