Wednesday, 18 September 2013

Rails validate model with attribute

Rails validate model with attribute

I need to do a custom validation that checks if the attribute being
updated is less than another attribute on that record. I tried doing this:
validates :team_size, :numericality => { :greater_than_or_equal_to =>
self.users.count }
But it comes back with the error:
NoMethodError (undefined method `users' for #<Class:0x007fcda9a548e8>):
I also tried doing a before_save hook with a method like this:
def validate_team_size
if self.team_size < self.users.count
errors[:base] << "Custom message."
end
end
But it just ignores it - I'm assuming because the team_size attribute
hasn't been updated yet so I'm checking the old value. Also tried using
after_save which is just before it commits but no luck either.

No comments:

Post a Comment