Controlling the order of rails validations

前端 未结 5 547
天命终不由人
天命终不由人 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:56

    I recall running into this issue quite some time ago, still unclear if validations order can be set and execution chain halted if a validation returns error.

    I don't think Rails offers this option. It makes sense; we want to show all of the errors on the record (incl. those that come after a failing, due to invalid input, validation).

    One possible approach is to validate only if the input to validate is present:

    def within_required_range?
      return unless [:attribute1, attribute2, ..].all?(&:present?)
    
      # check the calculations and return true or false here
    end
    

    Make it pretty & better structured (single responsibility) with Rails idiomatic validation options:

    validates :attribute1, :presence => true
    validates :attribute2, :presence => true
    # and so on through the attributes
    
    validate :calculations_ok?, if: :attributes_present?
    
    private
      def attributes_present?
        [:attribute1, attribute2, ..].all?(&:present?)
      end
    
      def calculations_ok?
        errors[:base] << "Not within required range" unless within_required_range?
      end
    
      def within_required_range?
        # check the calculations and return true or false here
      end
    

提交回复
热议问题