Rails 4自定义验证

时间:2014-03-06 10:44:21

标签: ruby-on-rails

我的自定义验证器有问题。我有一个模型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_daysfrom_days时,我收到以下错误:

undefined method `>=' for nil:NilClass

现在的目标是仅在from_daysto_days出现时使用此验证器,但我不知道该怎么做。有什么想法吗?

1 个答案:

答案 0 :(得分:2)

您应该设置:if选项:

validate :days_range_validation, :if => :days_ranges_present?

# ...
private

def days_ranges_present?
  to_days.present? && from_days.present?
end