Search code examples
ruby-on-railsrubyrails-activerecordrspec-rails

Ruby on Rails: Running custom validation function only when other properties are present


I want my custom validator to only run when the properties it uses are present.

# these are all dates
validates :start_time, presence: true
validates :end_time, presence: true
validates :deadline_visitor, presence: true
validates :deadline_host, presence: true

# these validate the above dates
validate :validate_all_dates
validate :validate_dates

example:

def validate_all_dates
  if self.start_time > self.end_time
    errors.add(:start_time, 'must be before or the same day as end time')
  end
end

fails because self.start_time and self.end_time are not present


Solution

  • You can add an if parameter to the validate method, this can check the conditions needed. That parameter can take either be a proc:

    validates :validate_all_dates, if: Proc.new { |model| model.start_time.presence }
    

    Or with a method:

    validate :validate_all_dates, if: :dates_present?
    
    def dates_present?
      start_time.presence && end_time.presence
    end
    

    Take a look at this guide for more details: Conditional Validation