6

这是不起作用的代码

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

目前,除了星期天,我在 db 中度过的所有日子。我正在尝试添加“星期日”,但出现错误“未包含在列表中”。

4

3 回答 3

8

validates_inclusion_of 没有区分大小写的参数,因此您可以创建自己的验证器(如果您使用的是 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/**/"]  
于 2011-03-24T00:31:25.493 回答
2

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

这会在运行验证之前缩小字段

于 2017-08-30T04:17:46.493 回答
-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
于 2011-03-24T01:33:54.993 回答