I have a model with an serialized attribute (array). I would like to validate the model only if each member of the array is included within the pre-determined options.
Example: I have a Person model which has a "mood" attribute. Users can have more than one mood, but each mood must be either 'happy', 'sad', 'tired' or 'angry'.
The model would be something like this:
class Person < ActiveRecord::Base
MOODS = %w[happy sad tired angry]
# validates :inclusion => { :in => MOODS }
attr_accessible :mood
serialize :mood
end
The commented validation doesn't work. Is there any way to make it work or do I need a custom validation?
(Note: I don't want to create a separate Mood model.)
class Person < ActiveRecord::Base
MOODS = %w[happy sad tired angry]
validate :mood_check
attr_accessible :mood
serialize :mood
protected
def mood_check
mood.each do |m|
errors.add(:mood, "#{m} is no a valid mood") unless MOODS.include? m
end
end
end
Leaving this here in case it helps anyone in the future - I've written a gem to better handle validating serialized attributes. You can just put those validations in a block syntax, the ways you might expect to:
class Person < ActiveRecord::Base
MOODS = %w[happy sad tired angry]
attr_accessible :mood
serialize :mood
validates_array_values :mood, inclusion: { in: MOODS }
end
https://github.com/brycesenz/validates_serialized
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With