简体   繁体   English

Rails验证两个字段之一(XOR)的存在

[英]Rails validations presence of either one of two fields (XOR)

How can I validate that either one of these values is present, but not both? 如何验证是否存在这些值之一,但不能同时存在?

  validates_presence_of :client_id, message: 'Please enter a value'
  validates_presence_of :agency_id, message: 'Please enter a value'

I looked on the rails guides and I think I need to use conditional validations, but I'm still a little stuck. 我查看了rails指南,我认为我需要使用条件验证,但仍然有些困难。

Try this 尝试这个

validates :client_id, presence: true, unless: :agency_id
validates :agency_id, presence: true, unless: :client_id

If you want to include the error message, you can do 如果要包含错误消息,可以执行

validates :client_id, presence: { message: "Must have a value" }, unless: :agency_id

You can read more about validation messages 您可以阅读有关验证消息的更多信息

If you use the unless syntax, you will get 2 errors: one when client_id and one when agency_id if both are Nil. 如果使用“除非”语法,则将出现2个错误:一个在client_id时错误,一个在agency_id时错误(如果两者均为Nil)。

You would need a custom method if you want only one error. 如果只需要一个错误,则需要一种自定义方法。 Guides: ActiveRecord Validation 指南:ActiveRecord验证

validate :client_or_agency

def client_or_agency
  errors.add(:client_id, "Either Client or Agency needs a value") unless client_id.present? || agency_id.present?
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM