RubyonRails 4.模型条件验证



我有一个带有一些验证规则的模型:

class Order < ActiveRecord::Base
  validates :zip_code, presence: true, length: {is: 5}, numericality: {only_integer: true, :greater_than => 0}
end

当zip_code为空时,我不需要执行其他zip_code验证(这是多余的,如果zip_code是空的,用户页面上的所有其他验证消息看起来都很奇怪)

我该如何实现这个逻辑?我需要验证length, is_integer and greater_than only if zip_code is not blank?,并且只需要在用户页面上显示zip_code can't be blank消息

您可以执行类似的操作

validates :zip_code, presence: true
validates :zip_code, length: {is: 5}, numericality: {only_integer: true, :greater_than => 0}, :if => :zip_code?

希望它能有所帮助!

最新更新