ruby on rails - validates_presence_of at least one of these associations -
a withdrawalaccount
record contains either sepaaccount
, internationalaccount
, paypalaccount
or otheraccount
. should @ least 1 of these. can not more one.
class withdrawalaccount < activerecord::base has_one :sepa_account has_one :international_account has_one :third_account has_one :fourth_account end
updated question: how can validate_presence_of
either 1 of them while allowing 1 of them present.
try:
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
to validate either 1 should prefer following method:
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
with more 2 attributes validate:
since xor not work more 2 attributes (a ^ b ^ c
) check attributes using loop:
def accounts_consistency attributes = [sepa_account, international_account, third_account, fourth_account] result = attributes.select |attr| !attr.nil? end unless result.count == 1 errors.add(:base, "options consistency error") end end
Comments
Post a Comment