Ruby on Rails:仅在存在其他属性时运行自定义验证功能

时间:2017-08-29 15:07:47

标签: ruby-on-rails ruby rails-activerecord rspec-rails

我希望自定义验证程序仅在其使用的属性存在时运行。

# 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

示例:

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

失败,因为self.start_timeself.end_time不存在

2 个答案:

答案 0 :(得分:3)

您可以向if方法添加validate参数,这可以检查所需的条件。该参数可以是proc:

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

或使用方法:

validate :validate_all_dates, if: :dates_present?

def dates_present?
  start_time.presence && end_time.presence
end

请查看本指南了解详情:Conditional Validation

答案 1 :(得分:0)

您可以在验证器本身中添加变量的存在:

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