I need a validation to check whether an attribute is less or equal than another (virtual) attribute of the same record. How can I do that?
Sample code (not working – NoMethodError):
attr_reader :virt
attr_accessible :virt
validates :my_attr, :numericality => {:only_integer => true, :less_or_equal => self.virt}
(please be gentle and explicit, I’m a RoR newb :])
Since those validation lines are going to be executed when the class definition is first encountered,
self.virtdoesn’t exist.You can usually pass in a lambda/proc instead that will be
called at validation time from the scope of the object:This still isn’t that great, though. A better route would be to just define your own validation method:
This is much cleaner and more explicit. Note that you don’t need to use
selfhere since there is no ambiguity (if you were setting you would need theself).