I've added validation to my Rails model for less_than
and greater_than
, but they obviously conflict each other.
I want to make sure Rails validates a field on model to never be 0. So less than OR greater than 0, but not both because that's not possible.
How can I do this?
Validations are used to ensure that only valid data is saved into your database. For example, it may be important to your application to ensure that every user provides a valid email address and mailing address. Model-level validations are the best way to ensure that only valid data is saved into your database.
Data validation (when done properly) ensures that data is clean, usable and accurate. Only validated data should be stored, imported or used and failing to do so can result either in applications failing, inaccurate outcomes (e.g. in the case of training models on poor data) or other potentially catastrophic issues.
If any validations fail, the object will be marked as invalid and Active Record will not perform the INSERT or UPDATE operation. This helps to avoid storing an invalid object in the database. You can choose to have specific validations run when an object is created, saved, or updated.
There is already a validator for this called numericality
http://edgeguides.rubyonrails.org/active_record_validations.html#numericality
class Player < ApplicationRecord
validates :salary, numericality: { other_than: 0 }
end
validate :non_zero
def non_zero
if self.field_name == 0
self.errors.add(:field_name, "Field can't be zero")
end
end
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With