How to perform an inclusion validation on a serialized attribute?
ruby-on-rails, serialization, validation
Solution
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
Problem
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.)