gpt4 book ai didi

ruby-on-rails - ruby rails : Running custom validation function only when other properties are present

转载 作者:数据小太阳 更新时间:2023-10-29 08:43:05 25 4
gpt4 key购买 nike

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

# 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 不存在

最佳答案

你可以在validate方法中添加一个if参数,这样可以检查需要的条件。该参数可以是一个过程:

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

关于ruby-on-rails - ruby rails : Running custom validation function only when other properties are present,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45942564/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com