验证一个或另一个字段的存在(XOR)

时间:2010-01-25 17:28:46

标签: ruby-on-rails

如何验证一个或另一个字段的存在,但不能同时验证两个字段和

7 个答案:

答案 0 :(得分:141)

如果您为数值验证添加条件,那么您的代码将起作用:

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

答案 1 :(得分:40)

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

例如:用于验证user_nameemail中的一个是否存在:

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

答案 2 :(得分:10)

rails 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

答案 3 :(得分:9)

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

答案 4 :(得分:3)

 validate :father_or_mother

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

 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

尝试上面的简单示例。

答案 5 :(得分:1)

我在下面回答了这个问题。在此示例中,: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

答案 6 :(得分:1)

使用Proc or Symbol with :if and :unless进行的验证将在验证发生之前立即调用。

因此,这两个字段之一的存在可能是这样的:

validates :charge,
  presence: true,
  if: ->(user){user.charge.present? || user.payment.present?}
validates :payment,
  presence: true,
  if: ->(user){user.payment.present? || user.charge.present?}

(示例代码)代码的最后一项为:if:unless,但是正如doc中所声明的那样,它会在验证发生之前立即被调用-因此,在此之后,可以进行另一次检查,如果条件匹配。