Rails Model Validation: i need validates_inclusion_of with case sensitive false?
Asked Answered
S

3

6

Here is code which is not working

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

Currently i have all of days in db except sunday. I am trying to add "Sunday", and getting errors "is not included in the list".

Sicken answered 24/3, 2011 at 0:19 Comment(1)
Interesting, I see the same thing using the new style validations: validates :day, inclusion:{in:%w(one two), case_sensitive:false}Vernacularize
R
8

validates_inclusion_of does not have a case_sensitive argument, so you can create your own validator(if you are using 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

and save this in your lib directory as:

lib/day_format_validator.rb

Then in your model, you can have:

validates :day, :day_format => true

Just make sure rails loads this lib file on startup by putting this in your config/application.rb:

config.autoload_paths += Dir["#{config.root}/lib/**/"]  
Reprisal answered 24/3, 2011 at 0:31 Comment(2)
Thank you so much, answer is represented very nicely.Sicken
If you want to use the standard, internationalized Rails error message, do object.errors.add(attribute, I18n.t!("errors.messages.inclusion")), which will use the built-in Rails locale file (eg, here's the english one for version 4.2.5: github.com/rails/rails/blob/v4.2.5/activemodel/lib/active_model/…)Hum
S
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

This downcases the field before running the validation

Sketchy answered 30/8, 2017 at 4:17 Comment(0)
S
-1

A little simple solution if not worried about separating validations in 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
Sicken answered 24/3, 2011 at 1:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.