Rails model validation: do I need validates_inclusion_of with case sensitive flag?

Here is the code that doesn't work

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 days in dB except Sunday. I am trying to add "sunday" and getting errors is not on the list.

+4
source share
3 answers

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

 validates :day, :day_format => true 

Just make sure the rails load this lib file at startup by putting it in your config / application.rb file:

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

 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 reduces the field before starting the test.

0
source

A small simple solution, if you do not disturb the separation of validation 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 
-1
source

Source: https://habr.com/ru/post/1345015/


All Articles