Validates_Inclusion_Of No Longer Working the Same in Rails 4.1

validates_inclusion_of no longer working the same in Rails 4.1?

try adding .keys ?

validates :time_zone, 
inclusion: {
in: ActiveSupport::TimeZone.zones_map.keys
}

Rails validation inclusion error 'not included in list'

  1. In rails you need to divide validators by comma:
    validates :client_status, presence: true, inclusion: { in: 0..2 }

  1. It has no sense to check presence, if you check on inclusion. So you can simplify your code by simple validation:
    validates :client_status, inclusion: { in: 0..2 }

ActiveRecord - validation :allow_blank is always active even if it has :unless

allow_blank does not accept a Hash, only a boolean, so you cannot write something like :allow_blank => {:unless => :student?}, as you can see in the source activemodel-4.1.2/lib/active_model/validator.rb

def validate(record)
attributes.each do |attribute|
value = record.read_attribute_for_validation(attribute)
next if (value.nil? && options[:allow_nil]) || (value.blank? && options[:allow_blank])
validate_each(record, attribute, value)
end
end

However what you want to achieve can be done in two lines:

class User < ActiveRecord::Base
validates_presence_of :school_grade, :if => :student?
validates :school_grade, :numericality =>{:only_integer =>true}, :allow_blank => true
end

Why is this Rails inclusion validation failing?

"string" is casted as an integer (as your status column is an integer) before validation

"string".to_i # => 0

You can avoid this by using the numericality validator :

validates :status, :presence => true, :numericality => { :only_integer => true }, :inclusion => {:in => VALID_VALUES}

BTW, you can use #valid? or #invalid? method instead of #save in your test

How do i specify and validate an enum in rails?

Create a globally accessible array of the options you want, then validate the value of your status column:

class Attend < ActiveRecord::Base

STATUS_OPTIONS = %w(yes no maybe)

validates :status, :inclusion => {:in => STATUS_OPTIONS}

end

You could then access the possible statuses via Attend::STATUS_OPTIONS

How to remove validation using instance_eval clause in Rails?

I found a solution, not sure how solid it is, but it works well in my case. @aVenger was actually close with his answer. It's just that the _validators accessor contains only information used for reflection, but not the actual validator callbacks! They are contained in the _validate_callbacks accessor, not to be confused with _validations_callbacks.

Dummy.class_eval do
_validators.reject!{ |key, _| key == :field }

_validate_callbacks.reject! do |callback|
callback.raw_filter.attributes == [:field]
end
end

This will remove all validators for :field. If you want to be more precise, you can reject the specific validator for _validators which is the same as the raw_filter accessor of validate callbacks.



Related Topics



Leave a reply



Submit