Controlling the order of rails validations

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

    I'm not sure it's guaranteed what order these validations get run in, as it might depend on how the attributes hash itself ends up ordered. You may be better off making your validate method more resilient and simply not run if some of the required data is missing. For example:

    def within_required_range?
      return if ([ a, b, c, d ].find(&:blank?))
    
      # ...
    end
    

    This will bail out if any of the variables a through d are blank, which includes nil, empty arrays or strings, and so forth.

提交回复
热议问题