Rails模型验证:我需要validates_inclusion_of,区分大小写错误?

时间:2011-03-24 00:19:11

标签: ruby-on-rails validation model case-sensitive validates-uniqueness-of

这是无效的代码

    class WeekDay < ActiveRecord::Base
           validates_inclusion_of :day, :in => %w(sunday monday tuesday wednesday thursday friday saturday), :case_sensitive => false
    end

目前我在db中的所有日子除了星期日。我试图添加“星期日”,并获得错误“不包括在列表中”。

3 个答案:

答案 0 :(得分:8)

validates_inclusion_of没有case_sensitive参数,因此您可以创建自己的验证器(如果您使用的是Rails 3):

class DayFormatValidator < ActiveModel::EachValidator
  def validate_each(object, attribute, value)
    unless %w(sunday monday tuesday wednesday thursday friday saturday).include?(value.downcase)
      object.errors[attribute] << (options[:message] || "is not a proper day.") 
    end
  end
end

并将其保存在lib目录中:

lib/day_format_validator.rb

然后在您的模型中,您可以:

validates :day, :day_format => true

只需确保rails在启动时加载此lib文件,方法是将其放在config / application.rb中:

config.autoload_paths += Dir["#{config.root}/lib/**/"]  

答案 1 :(得分:1)

&#13;
&#13;
class WeekDay < ActiveRecord::Base
  
  before_validation :downcase_fields
  
  validates_inclusion_of :day, :in => %w(sunday monday tuesday wednesday thursday friday saturday)
    
  def downcase_fields
    self.day.downcase!
  end
  
end
&#13;
&#13;
&#13;

这会在运行验证

之前对该字段进行下调

答案 2 :(得分:-1)

一个简单的解决方案,如果不担心在lib中分离验证

    class WeekDay < ActiveRecord::Base
        validate :validate_day
            def validate_day
            if !self.day.nil?
                errors.add(:day, "is not included in the list") unless  %w(sunday monday tuesday wednesday thursday friday saturday).include?(self.day.downcase)
                    end
            end 
     end