Validate singularity of a string in rails

Go To


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.

2012-04-04 18:31
by Tony Beninate


One way would be to leverage the singularize method.

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") 

Then in your model:

validates :column_name, :singular => true

Credit: Basic structure of a custom validator extracted from Ryan's Railscast #211

2012-04-04 18:49
by Nathan
Thanks @Nathan. Just what I was looking for - Tony Beninate 2012-04-04 18:51