代码之家  ›  专栏  ›  技术社区  ›  vinibrsl

如何处理Rails上的依赖验证?

  •  0
  • vinibrsl  · 技术社区  · 6 年前

    我的模型上有一些活动记录验证:

    class Product < ApplicationRecord
      validates :name, presence: true, length: { is: 10 }
    end
    

    看起来不错。它验证了 name 不是 nil "" custom validation ,我要加上 validate

    class Product < ApplicationRecord
      validates :name, presence: true, length: { is: 10 }
      validate :name_must_start_with_abc
    
      private
    
      def name_must_start_with_abc
        unless name.start_with?('abc')
          self.errors['name'] << 'must start with "abc"'
        end
      end
    end
    

    问题是:当 名称 presence_of name_must_start_with_abc ,提出 NoMethodError .

    为了克服这个问题,我必须在

    def name_must_start_with_abc
      return if name.nil?
    
      unless name.start_with?('abc')
        self.errors['name'] << 'must start with "abc"'
      end
    end
    

    这就是我不想做的,因为如果我添加更多的“依赖”验证,我必须在每个自定义验证方法上重新验证它。

    如何处理Rails上的依赖验证?有没有办法防止在其他验证未通过时调用自定义验证?

    2 回复  |  直到 6 年前
        1
  •  1
  •   P. Boro    6 年前

    我认为没有完美的解决方案,除非您将所有验证都编写为自定义方法。我经常使用的方法:

    class Product < ApplicationRecord
      validates :name, presence: true, length: { is: 10 }
      validate :name_custom_validator
    
      private
    
      def name_custom_validator
        return if errors.include?(:name)
    
        # validation code
      end
    end
    

    通过这种方式,您可以将尽可能多的验证添加到 :name

        2
  •  0
  •   Ashik Salman    6 年前
    class Product < ApplicationRecord
      validates :name, presence: true, length: { is: 10 }
      validate :name_must_start_with_abc, unless: Proc.new { name.nil? }
    
      private
    
      def name_must_start_with_abc
        unless name.start_with?('abc')
          self.errors['name'] << 'must start with "abc"'
        end
      end
    end
    

    请检查 allow_blank , :allow_nil conditional validation