반응형
한 필드 또는 다른 필드의 존재 여부 확인 (XOR)
하나 또는 다른 필드의 존재 여부를 확인하는 방법은 무엇입니까?
다음과 같이 수치 유효성 검사에 조건을 추가하면 코드가 작동합니다.
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+에서는 이것이 더 관용적이라고 생각합니다.
예 : user_name
또는 중 하나가 있는지 확인하려면 email
:
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
참고 URL : https://stackoverflow.com/questions/2134188/validate-presence-of-one-field-or-another-xor
반응형
'IT박스' 카테고리의 다른 글
숭고한 텍스트의 정규식 : 개행 문자를 포함하여 모든 문자와 일치합니까? (0) | 2020.09.19 |
---|---|
ssh가 bash에서 while-loop에서 나옴 (0) | 2020.09.18 |
SAFESEH 이미지 C ++에 대해 안전하지 않은 모듈 (0) | 2020.09.18 |
"AsseticBundle 구성에 myBundle 추가"symfony2 예외를 수정하려면 어떻게해야합니까? (0) | 2020.09.18 |
Objective-C 코드가 Class에서 신속한 확장을 호출 할 수 있습니까? (0) | 2020.09.18 |