Rails 3validation:presence => false
这是我期望的一个非常简单的问题,但我无法在指南或其他地方找到明确的答案。
我在ActiveRecord上有两个属性。 我想要一个存在,另一个是零或空字符串。
我该怎么做相同的:presence => false? 我想确保值为零。
validates :first_attribute, :presence => true, :if => "second_attribute.blank?" validates :second_attribute, :presence => true, :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, :presence => false, :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, :presence => true, :if => "second_attribute.blank?" validates :second_attribute, :presence => true, :if => "first_attribute.blank?" validates :first_attribute, :no_presence => true, :if => "!second_attribute.blank?" validates :second_attribute, :no_presence => true, :if => "!first_attribute.blank?"
为了允许对象有效,当且仅当特定属性为nil时,您可以使用“包含”而不是创建自己的方法。
validates :name, inclusion: { in: [nil] }
这适用于Rails 3.Rails 4解决方案更加优雅:
validates :name, absence: true
使用自定义validation。
validate :validate_method # validate if which one required other should be blank def validate_method errors.add(:field, :blank) if condition end
它看起来像:length => {:is => 0}适用于我需要的东西。
validates :first_attribute, :length => {:is => 0 }, :unless => "second_attribute.blank?"
尝试:
validates :first_attribute, :presence => {:if => second_attribute.blank?} validates :second_attribute, :presence => {:if => (first_attribute.blank? && second_attribute.blank? )}
希望有所帮助。