4

這裏是一個沒有工作Rails模型驗證:我需要validates_inclusion_of與區分大小寫錯誤嗎?

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

目前,我有所有DB天的週日除外代碼。我正在嘗試添加「星期天」,並且收到錯誤「未包含在列表中」。

+0

有趣的是,我使用新的樣式驗證也是一樣:'validates:day,inclusion:{in:%w(one two),case_sensitive:false}' – SooDesuNe 2011-03-24 00:31:43

回答

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 

只要確保軌道加載這個lib文件在明星TUP通過把這個在你的config/application.rb中:

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

非常感謝,答案非常好。 – 2011-03-24 01:00:28

+0

如果您想使用標準的國際化Rails錯誤消息,請執行'object.errors.add(attribute,I18n.t!(「errors.messages.inclusion」))',它將使用內置的Rails語言環境文件(例如,以下是4.2.5版的英文版:https://github.com/rails/rails/blob/v4.2.5/activemodel/lib/active_model/locale/en.yml#L9) – 2016-03-03 14:59:20

-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 
0

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

這downcases的字段在運行驗證之前