Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to perform an inclusion validation on a serialized attribute?

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.)

like image 330
Luciano Avatar asked May 28 '12 01:05

Luciano


2 Answers

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
like image 81
Viktor Trón Avatar answered Nov 03 '22 17:11

Viktor Trón


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

like image 2
Bryce Avatar answered Nov 03 '22 16:11

Bryce