Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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".

like image 388
Maddy.Shik Avatar asked Mar 24 '11 00:03

Maddy.Shik


2 Answers

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/**/"]  
like image 170
Mike Lewis Avatar answered Oct 14 '22 02:10

Mike Lewis


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

like image 26
E Pierre Avatar answered Oct 14 '22 01:10

E Pierre