How to perform inclusion check in serialized attribute?

I have a model with a serialized attribute (array). I would like to test the model only if each member of the array is included in predefined parameters.

Example: I have a Person model that has the "mood" attribute. Users can have more than one mood, but each mood should be “happy,” “sad,” “tired,” or “angry.”

The model will look something like this:

class Person < ActiveRecord::Base
  MOODS = %w[happy sad tired angry]
  # validates :inclusion => { :in => MOODS } 

  attr_accessible :mood
  serialize :mood
end

Commented verification does not work. Is there a way to make it work, or do I need a special check?

(Note: I do not want to create a separate mood model.)

+5
source share
2
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
+8

, - , , . , :

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

+2

All Articles