The Spaghetti Refactory Established 2015

Adding error messages in custom Rails validate methods

If you've ever needed custom validators in Rails, this is what you need in your methods when something doesn't pass a validation:

errors.add(:base, 'A star count score must be within the range of 0 to 5.')

This will add that error message to object.errorsIf you tweak it slightly to this, it becomes more extensible:

errors.add(:star_count, 'score must be within the range of 0 to 5.')

You can call object.errors.full_messages.each do |message| and it will basically output this: “#{:star_count.to_s.capitalize} score must be within the range of 0 to 5.”

Tags