我有一个包含数字范围和描述[min_val,max_val,name]的对象。 我需要验证min_val< MAX_VAL。但是,如果其中一个是空白的,我会得到一个零比较错误,相反,我想告诉用户需要一个数字。
另外,如何更改数字的错误消息?
validates :min_val, :presence => true, :numericality => {:greater_than => 0, :less_than => :max_val}
validates :max_val, :presence => true, :numericality => {:greater_than => 0, :greater_than => :min_val}
validates :name, :presence => true, :if => Proc.new { |r| !r.min_val.nil? || !r.max_val.nil? }
答案 0 :(得分:3)
您可以使用:message指定自定义错误消息。
validates :max_val, :presence => true, :numericality => {:greater_than => 0, :message => " is an invalid number."}
validates :min_val, :presence => true, :numericality => {:greater_than => 0, :message => " is an invalid number."}
validate do |record|
record.errors.add_to_base("The min_val should be less than max_val") if min_val.to_i >= max_val.to_i
end
validates :name, :presence => true, :if => Proc.new { |r| !r.min_val.nil? || !r.max_val.nil? }