我希望自定义验证程序仅在其使用的属性存在时运行。
# 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_time
和self.end_time
不存在
答案 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