我需要为字段创建验证,以确保它只有一个字。
这是我所拥有的,但它只验证长度是1个字符,而不是一个字
validates_length_of :name, maximum: 1, too_many_words: 'Please choose a name with only one word', tokenizer: ->(str) { str.scan(/\w+/) }
我在这里找到了我正在使用的示例http://www.rubydoc.info/docs/rails/4.1.7/ActiveModel/Validations/HelperMethods:validates_length_of
答案 0 :(得分:2)
我实际上在http://guides.rubyonrails.org/active_record_validations.html
找到了答案validates :name, length: {
maximum: 1,
tokenizer: lambda { |str| str.split(/\s+/) },
too_long: "Please choose a name that is only %{count} word."
}
答案 1 :(得分:2)
validates :name,
:presence => true,
:uniqueness => true,
:length => {
:maximum => 1,
:tokenizer => lambda {|str| str.scan(/\w+/)},
:too_long => "Name must be one word."
}