Anyone know if there is anything built into rails to the effect of
validates_signularity_of :string? I can't find any documentation of anything like this, but just wanted to check. I want to validate that a string the user can enter in is always a singular word.
One way would be to leverage the
If singularizing a string results in the same string, the string is already singular. Otherwise, it is plural.
A custom validator like the following might work:
class SingularValidator < ActiveModel::EachValidator def validate_each(object, attribute, value) unless value.to_s.singularize == value object.errors[attribute] << (options[:message] || "is not singular") end end end
Then in your model:
validates :column_name, :singular => true
Credit: Basic structure of a custom validator extracted from Ryan's Railscast #211