我正在尝试创建一个验证语句,如果存在service_area
,则验证对象除service_area_radius==0
这是我创建的语句,它不起作用:
validates :service_area, :presence => true, unless: "service_area_radius==0"
答案 0 :(得分:0)
http://railscasts.com/episodes/41-conditional-validations
像这样:
validates_presence_of :password, :if => :should_validate_password?
validates_presence_of :country
validates_presence_of :state, :if => :in_us?
attr_accessor :updating_password
def in_us?
country == 'US'
end
def should_validate_password?
updating_password || new_record?
end
答案 1 :(得分:0)
validates :service_area,
presence: {message: "Area Radius is missing."}, if: :radius_found?
private
def radius_found?
service_area_radius > 0
end
如果radius_found,将执行service_area的验证?返回true。
radius_found?当service_area_radius(属性)保持值>时将返回true 0
当验证失败时,使用message:选项添加自定义消息。