Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails Validates less than 0 or greater than 0, or field not equal to 0

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?

like image 337
Noah Avatar asked Apr 14 '16 19:04

Noah


People also ask

What are validations in Rails?

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.

Why must you validate data before persisting it?

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.

Can we save an object in DB if its validations do not pass?

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.


2 Answers

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
like image 149
Kalman Avatar answered Nov 09 '22 09:11

Kalman


validate :non_zero

def non_zero
  if self.field_name == 0
     self.errors.add(:field_name, "Field can't be zero")
  end
end
like image 6
toddmetheny Avatar answered Nov 09 '22 07:11

toddmetheny