简体   繁体   English

自定义表单验证导轨

[英]Custom form Validation Rails

I am wondering if i have set up my method incorrectly as my validation attempt is being ignored halfway through the method. 我想知道我是否正确设置了我的方法,因为我的验证尝试在该方法的一半被忽略了。 (i have provided a basic example, i want to get this working before adding more) (我提供了一个基本示例,我想在添加更多内容之前使其正常工作)

I have two variations of a form all belonging to the same object. 我有两种形式的所有形式都属于同一个对象。 The forms are differentiated by a column animal_type as you can see in my method 如我的方法所示,表格的形式是由animal_type列区分的

 class Animal < ActiveRecord::Base
   before_save :animal_form_validation


  private
  def animal_form_validation
    if self.animal_type == 'Dog'
      ap('Im validating the dog Form')
        if self.name.length <= 0
          errors.add(:name, "Name cannot be blank")
        end
    elsif self.animal_type == 'Cat'
      ap('Im validating the cat form')
        if self.name.length <= 0
          errors.add(:name, "Name cannot be blank")
        end
    end
  end
end

whether i am submitting a cat or dog i get the correct message in the console (using awesome print), so the method is running and knows which form im submitting, but as for the next if statement it is being ignored. 无论我要提交的是猫还是狗,我都会在控制台中得到正确的消息(使用真棒打印),因此该方法正在运行,并且知道我正在提交哪种表格,但是对于下一个if语句,它将被忽略。

So i have an error with my syntax? 所以我的语法有错误吗? or am i calling the wrong validation check on the name field ? 还是我在名称字段上调用了错误的验证检查?

Thanks 谢谢

Use validation instead of a before_save callback: 使用验证而不是before_save回调:

validate :animal_form_validation

Also, you can add conditional validation if you're checking the same condition prior to validating. 另外,如果在验证之前检查相同条件,则可以添加条件验证。 Example: validate :animal_form_validation, if: name.blank? 示例: validate :animal_form_validation, if: name.blank?

You are calling those validation in before_save , which is after the record has been validated and is assumed to be valid. 您正在before_save中调用这些验证,此验证是在记录经过验证并假定为有效之后。 You need to run it as a validation: 您需要运行它作为验证:

validate :animal_form_validation

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

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