Controlling the order of rails validations

前端 未结 5 565
天命终不由人
天命终不由人 2020-12-02 22:05

I have a rails model which has 7 numeric attributes filled in by the user via a form.

I need to validate the presence of each of these attributes which is obviously

5条回答
  •  感情败类
    2020-12-02 22:51

    An alternative for slightly more complex situations would be to create a helper method which runs the validations for the dependent attributes first. Then you can make your :calculations_ok? validation run conditionally.

    validates :attribute1, :presence => true
    validates :attribute2, :presence => true
    ...
    validates :attribute7, :presence => true
    
    validate :calculations_ok?, :unless => Proc.new { |a| a.dependent_attributes_valid? }
    
    def dependent_attributes_valid?
      [:attribute1, ..., :attribute7].each do |field|
        self.class.validators_on(field).each { |v| v.validate(self) }
        return false if self.errors.messages[field].present?
      end
      return true
    end
    

    I had to create something like this for a project because the validations on the dependent attributes were quite complex. My equivalent of :calculations_ok? would throw an exception if the dependent attributes didn't validate properly.

    Advantages:

    • relatively DRY, especially if your validations are complex
    • ensures that your errors array reports the right failed validation instead of the macro-validation
    • automatically includes any additional validations on the dependent attributes you add later

    Caveats:

    • potentially runs all validations twice
    • you may not want all validations to run on the dependent attributes

提交回复
热议问题