validation是否存在一个或另一个字段(XOR)

我如何validation一个字段或另一个字段的存在,但不是两个字段,至less有一个?

你的代码将工作,如果你添加条件的数值validation,如下所示:

class Transaction < ActiveRecord::Base validates_presence_of :date validates_presence_of :name validates_numericality_of :charge, allow_nil: true validates_numericality_of :payment, allow_nil: true validate :charge_xor_payment private def charge_xor_payment unless charge.blank? ^ payment.blank? errors.add(:base, "Specify a charge or a payment, not both") end end end 

我认为这在Rails 3+中更加惯用:

例如:用于validationuser_nameemail是否存在:

 validates :user_name, presence: true, unless: ->(user){user.email.present?} validates :email, presence: true, unless: ->(user){user.user_name.present?} 

导轨3的示例

 class Transaction < ActiveRecord::Base validates_presence_of :date validates_presence_of :name validates_numericality_of :charge, :unless => proc{|obj| obj.charge.blank?} validates_numericality_of :payment, :unless => proc{|obj| obj.payment.blank?} validate :charge_xor_payment private def charge_xor_payment if !(charge.blank? ^ payment.blank?) errors[:base] << "Specify a charge or a payment, not both" end end end 
 class Transaction < ActiveRecord::Base validates_presence_of :date validates_presence_of :name validates_numericality_of :charge, allow_nil: true validates_numericality_of :payment, allow_nil: true validate :charge_xor_payment private def charge_xor_payment if [charge, payment].compact.count != 1 errors.add(:base, "Specify a charge or a payment, not both") end end end 

你甚至可以用3个或更多的值来做到这一点:

 if [month_day, week_day, hour].compact.count != 1 
  validate :father_or_mother 

#姓氏或母亲姓氏是强制性的

  def father_or_mother if father_last_name == "Last Name" or father_last_name.blank? errors.add(:father_last_name, "cant blank") errors.add(:mother_last_name, "cant blank") end end 

试试上面的简单例子。

我在下面回答了这个问题。 在这个例子中:description:keywords是其中一个不为空的字段:

  validate :some_was_present belongs_to :seo_customable, polymorphic: true def some_was_present desc = description.blank? errors.add(desc ? :description : :keywords, t('errors.messages.blank')) if desc && keywords.blank? end