Checks that one value is not equal to another

Is there a way to verify that one text field is not equal to another before saving the record? I have two text fields with integers in them, and they cannot be the same for the record to be valid.

+6
source share
2 answers

You can add a custom check:

class Something validate :fields_a_and_b_are_different def fields_a_and_b_are_different if self.a == self.b errors.add(:a, 'must be different to b') errors.add(:b, 'must be different to a') end end 

This will be called every time your object is checked (either explicitly, or when you save it with a check), and adds an error to both fields. You may need an error in both fields to make them different in form.

Otherwise, you can simply add a basic error:

 errors.add(:base, 'a must be different to b') 
+8
source

In your model:

 validate :text_fields_are_not_equal def text_fields_are_not_equal self.errors.add(:base, 'Text_field1 and text_field2 cannot be equal.') if self.text_field1 == self.text_field2 end 
+5
source

Source: https://habr.com/ru/post/909218/


All Articles