Ryan Rebo
Ryan Rebo

Reputation: 1318

Restraint/validation to not allow negative integer

What would be a way to not allow negative numbers for an integer column?

I thought maybe this would work, but it didn't:

validates_numericality_of :rolling_rank, :only_integer => true, :greater_than_or_equal_to => 0

EDIT:

In context, there is a nightly cron that does a bunch of calculating, and uses MyObject.decrement!(:rolling_rank, by = calculated_value). If the decrement tries to go into the negative, I want it to stop (and save) at zero.

Upvotes: 1

Views: 1725

Answers (1)

Jordan Running
Jordan Running

Reputation: 106027

From the docs for decrement! (emphasis mine):

decrement!(attribute, by = 1)

Wrapper around decrement that saves the record. This method differs from its non-bang version in that it passes through the attribute setter. Saving is not subjected to validation checks. Returns true if the record could be saved.

If this is what you want...

If the decrement tries to go into the negative, I want it to stop (and save) at zero.

...then you don't want a validation.

I think the simplest solution is to override the rolling_rank= setter:

def rolling_rank=(value)
  value = 0 if value < 0
  super
end

Since decrement! "passes [the value] through the attribute setter," this will be invoked before the record is persisted.

Upvotes: 1

Related Questions