Search code examples
ruby-on-railsvalidates-uniqueness-of

Rails Models Validation 1 Word


I try to add a validation from a blog category only limited at 1 word.

But I try this length: { maximum: 1 }

I doesn't work. Is there a validation to validaes only one word and not uniqueness?

Thank you for your answers


Solution

  • You can make a custom validation:

    validates :category, uniqueness: true
    validate :category_in_1_word
    
    private
    
    def category_in_1_word
      if category.to_s.squish.split.size != 1
        errors.add(:category, 'must be 1 word')
      end
    end