Reputation: 315
I want to make sure that numbers coming into this object are divisible by 3. How do I use the validate on the model to prevent invalid input?
Thanks!
Upvotes: 1
Views: 464
Reputation: 411
You can write your own simple validation method for this like so:
validate :divisible_by_three
def divisible_by_three
unless attribute%3 == 0
self.errors.add(:attribute, "is not divisible by 3")
end
end
I don't think any of the built in rails methods so this is probably the best solution.
Tom
Upvotes: 0
Reputation: 11647
Try this:
# your_model.rb
validate :only_valid_numbers
private
def only_valid_numbers
if (self.number % 3) != 0
self.errors[:base] << "Number must be divisible by 3!"
end
end
Remember that 0 % 3
will be 0, so if you don't want to allow that, change the if statement to:
if self.number != 0 and ...etc...
Upvotes: 3