Warning: file_get_contents(/data/phpspider/zhask/data//catemap/5/ruby/23.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/git/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails 在Rails中,如何编写验证规则来验证两个字段是否都应该存在?_Ruby On Rails_Ruby_Validation_Model_Ruby On Rails 5 - Fatal编程技术网

Ruby on rails 在Rails中,如何编写验证规则来验证两个字段是否都应该存在?

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_

我正在使用RubyonRails5。我有一个带有两个字段的模型

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
查阅参考资料