尝试:
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