Rails validating values in array
I don't think that default Rails validators will do the trick here, you can do this though:
validate :validate_wdays
def validate_wdays
if !wdays.is_a?(Array) || wdays.any?{|d| !(0..6).include?(d)}
errors.add(:wdays, :invalid)
end
end
I created this gem: https://github.com/rafaelbiriba/active_model_validates_intersection_of
Basicaly, you can use like:
class User < ActiveRecord::Base
DEFAULT_PERMISSION = ["read", "write", "share"]
validates_intersection_of :permission, in: DEFAULT_PERMISSION
end
and if you try:
user = User.new(permission: ["read", "share"])
user.valid? #true
user = User.new(permission: ["read", "admin"])
user.valid? #false
Enjoy! Comments, pull requests and feedbacks is always welcome.
I'm not certain whether there are easier ways to handle this within the existing Rails validation structure. You've got an odd case that the validators weren't really built to handle. You might need to write a custom validator for something like this (assuming an existing validation extension gem isn't available). Something like this:
class ArrayInRangeValidator < ActiveModel::EachValidator
def validate_each(record, attribute, valueArray)
valueArray.each do |value|
record.errors.add "#{attribute} - #{value}", (options[:message] || "is not in the acceptable range") unless (1..6).include?(value)
end
end
end
and then in your model:
class Schedule < ActiveRecord::Base
include ActiveModel::Validations
validates :wdays, :presence => true, :array_in_range => true
... other model stuff
end
The accepted answer didn't really do this correctly in my opinion. If someone sets wdays = 'meow'
it'll set it to empty array wdays == []
without warning.
Type Casting is happening you ask for wdays
in that method. It's already converting the data into an array if it's invalid.
wdays_before_type_cast
should be used instead of wdays
when checking type.
See _before_type_cast
validate :validate_wdays
def validate_wdays
errors.add(:wdays, :invalid) if wdays_changed? && !wdays_before_type_cast.is_a?(Array)
errors.add(:wdays, :invalid) if wdays.any? { |d| (0..6).exclude?(d) }
end