以下是我期待的一个完全直截了当的问题,但是我在“指南”或其他地方找不到确切的答案.
我在ActiveRecord上有两个属性.我想要一个是存在的,另一个是零或一个空白的字符串.
我如何做等同于:presence =>假?我想确保该值为零.
validates :first_attribute,:presence => true,:if => "second_attribute.blank?" validates :second_attribute,:if => "first_attribute.blank?" # The two lines below fail because 'false' is an invalid option validates :first_attribute,:presence => false,:if => "!second_attribute.blank?" validates :second_attribute,:if => "!first_attribute.blank?"
或者也许有更优雅的方式来做到这一点…
我正在运行Rails 3.0.9
解决方法
class NoPresenceValidator < ActiveModel::EachValidator def validate_each(record,attribute,value) record.errors[attribute] << (options[:message] || 'must be blank') unless record.send(attribute).blank? end end validates :first_attribute,:if => "first_attribute.blank?" validates :first_attribute,:no_presence => true,:if => "!first_attribute.blank?"