Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/64.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 为什么不是';第一次验证不检查第二次验证吗?_Ruby On Rails_Activerecord - Fatal编程技术网

Ruby on rails 为什么不是';第一次验证不检查第二次验证吗?

Ruby on rails 为什么不是';第一次验证不检查第二次验证吗?,ruby-on-rails,activerecord,Ruby On Rails,Activerecord,考虑到这一点,包括在几个类别中: concern: Helpful do included do validates :first_reference_id, :second_reference_id, presence: true validates :same_parent end def same_parent unless first_reference.parent == second_reference.parent errors.a

考虑到这一点,包括在几个类别中:

concern: Helpful do
  included do
    validates :first_reference_id, :second_reference_id, presence: true
    validates :same_parent
  end

  def same_parent
    unless first_reference.parent == second_reference.parent
      errors.add(:base, 'Parent error')
    end
  end
end

什么会导致在第二次验证中出现nil:NilClass的
命名错误:未定义\u方法“父级”

简单的答案是验证不会短路。每个验证过程独立于其他验证的结果

为了防止出现错误,请将第二次验证更新为

def same_parent
  if first_reference &&
      second_reference &&
      first_reference.parent != second_reference.parent
    errors.add(:base, 'Parent error')
  end
end
这样,第一次验证将捕获其中一个引用为空的情况,而此验证将仅捕获两个引用都存在但它们没有相同父引用的情况