Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In ruby on rails, how can I validate multiple attributes for a range of values?

I have about 10 attributes in a table that take a number as a value, for each attributes I'd like to validate whether or not a number between 1 - 100 are passed into an input. Any thoughts I can reduce the code below to a one method validation?

Currently, for each attribute, I am doing this;

validates_numericality_of :valueone, :less_than_or_equal_to => 100 validates_numericality_of :valuetwo, :less_than_or_equal_to => 100 validates_numericality_of :valuethree, :less_than_or_equal_to => 100

etc.

Any help is much appreciated. Thanks.

like image 699
Nicholas Alek Avatar asked Nov 08 '12 23:11

Nicholas Alek


1 Answers

I think you should use constants. It will produce a more elegant code like so:

class Whatever
  MIN = 1
  MAX = 100

  validates :valueone, :valuetwo, :valuethree, :length => { :within => MIN..MAX }
end

You can list all attributes with the same validation as above.

This should do it. =)

like image 57
Paulo Henrique Avatar answered Nov 15 '22 06:11

Paulo Henrique