Ruby on rails 在Rails中,如何编写验证规则来验证两个字段是否都应该存在?
我正在使用RubyonRails5。我有一个带有两个字段的模型Ruby on rails 在Rails中,如何编写验证规则来验证两个字段是否都应该存在?,ruby-on-rails,ruby,validation,model,ruby-on-rails-5,Ruby On Rails,Ruby,Validation,Model,Ruby On Rails 5,我正在使用RubyonRails5。我有一个带有两个字段的模型 first_name last_name 如何编写验证规则来指定如果一个存在,那么另一个也必须存在?如果它们都是空白的就可以了,但基本上它们要么存在要么都不存在。如何编写规则?这里有两个选项。您可以使用条件验证或编写自定义验证来执行此检查 使用条件验证: validates :first_name, presence: true, if: -> {last_name.present?} validate :both_or_
first_name
last_name
如何编写验证规则来指定如果一个存在,那么另一个也必须存在?如果它们都是空白的就可以了,但基本上它们要么存在要么都不存在。如何编写规则?这里有两个选项。您可以使用条件验证或编写自定义验证来执行此检查 使用条件验证:
validates :first_name, presence: true, if: -> {last_name.present?}
validate :both_or_neither_present
# ...
def both_or_neither_present
# if only one of the fields is present
if (first_name.present? ^ last_name.present?)
errors.add(:name, "Only part of the name was given")
end
end
使用自定义验证:
validates :first_name, presence: true, if: -> {last_name.present?}
validate :both_or_neither_present
# ...
def both_or_neither_present
# if only one of the fields is present
if (first_name.present? ^ last_name.present?)
errors.add(:name, "Only part of the name was given")
end
end
使用第二个,您可以编写自定义错误消息。对于第一个,错误将始终出现在:first_name属性上。要添加到Glyoko的帖子:
validates :first_name, presence: { 'Last name is missing' }, if: -> {last_name.present?}
validates :last_name, presence: { 'First name is missing' }, if: -> {first_name.present?}
这是有用的
validates_presence_of :last_name, :if => :first_name? (or vice versa)
然后需要创建一个first_name方法,该方法返回一个布尔值,类似于:
def first_name?
first_name.present?
#If the user have a first_name Validates that the specified attributes is not blank
end
查阅参考资料