我的自定义验证器有问题。我有一个模型Price
,看起来像这样:
class Price < ActiveRecord::Base
belongs_to :car
validates :from_days, :to_days, :netto_price, presence: true, numericality: true
validate :days_range_validation
private
def days_range_validation
unless to_days > from_days
errors[:to_days] << I18n.t('price.must_be_greater')
end
end
end
问题是,当我在表单中留下to_days
和from_days
时,我收到以下错误:
undefined method `>=' for nil:NilClass
现在的目标是仅在from_days
和to_days
出现时使用此验证器,但我不知道该怎么做。有什么想法吗?
答案 0 :(得分:2)
您应该设置:if
选项:
validate :days_range_validation, :if => :days_ranges_present?
# ...
private
def days_ranges_present?
to_days.present? && from_days.present?
end