0

记录WithdrawalAccount包含SepaAccountInternationalAccountPayPalAccount。_ OtherAccount至少应该是其中之一。不能超过一个。

class WithdrawalAccount < ActiveRecord::Base
  has_one :sepa_account
  has_one :international_account
  has_one :third_account
  has_one :fourth_account
end

更新的问题: 我怎样才能validate_presence_of在只允许其中一个存在的情况下使用其中之一。

4

2 回答 2

3

尝试:

class WithdrawalAccount < ActiveRecord::Base
  has_one :sepa_account
  has_one :international_account

  validates :sepa_account,          presence: true, if: ->(instance) { instance.international_account.blank? }
  validates :international_account, presence: true, if: ->(instance) { instance.sepa_account.blank? }
end

要验证任何一个,您应该更喜欢以下方法:

class WithdrawalAccount < ActiveRecord::Base

  validate :accounts_consistency

  private

  def accounts_consistency
    # XOR operator more information here http://en.wikipedia.org/wiki/Xor
    unless sepa_account.blank? ^ international_account.blank?
      errors.add(:base, "options consistency error")
    end
  end
end

需要验证的属性超过 2 个:

由于 XOR不能处理超过 2 个属性 ( a ^ b ^ c) 我们可以使用循环检查属性:

def accounts_consistency
  attributes = [sepa_account, international_account, third_account, fourth_account]
  result = attributes.select do |attr|
    !attr.nil?
  end

  unless result.count == 1
    errors.add(:base, "options consistency error")
  end
end
于 2013-08-16T07:25:03.887 回答
1

你可以这样做

validate :account_validation

private

def account_validation
  if !(sepa_account.blank? ^ international_account.blank?)
    errors.add_to_base("Specify an Account")
  end
end

这里有答案(验证一个或另一个字段的存在(XOR)

于 2013-08-16T07:26:27.023 回答