Search code examples
ruby-on-railsrubyvalidationattributesvirtual

Rails - How can I sum all the fields and use the sum as a validation before entering values in database?


I have a form containing multiple fields that have integer inputs. I have basic validation on the fields like presence, inclusion, and numericality. The part that I am stuck at however is checking that the sum of all the fields is equal to 100. I need to find a way to sum up all the values in the fields and ensure they add up to one hundred with a validator. I considered using a virtual attribute that would do the summing of the fields, and then use a validator on that value, however, I am not exactly sure how to implement it. Any help would be greatly appreciated.

Thanks, A confused rails beginner


Solution

  • You can use a custom validation method: see http://guides.rubyonrails.org/active_record_validations_callbacks.html#custom-methods for more.

    So for instance try something like the following where field1 and field2 are attributes on your model:

    class Klass < ActiveRecord::Base
    
      validate :sum_equals_100
    
      def sum_equals_100
         if field1 + field2 != 100
           errors.add(:base, 'fields must sum to 100')
         end
      end
    end