Checking Complete Rails Data

I have a field that is serialized in YAML through the default AR behavior. It is currently in the hash array for an example:

[{'name' => 'hi', 'url' => 'bye'}, 
 {'name' => 'hi', 'url' => 'bye'}, 
 {'name' => 'hi', 'url' => 'bye'}]

Can I use some basic AR checks for some of these fields?

+5
source share
2 answers

Yes, use the method validates_each

serialize :urls
validates_each :urls do |record, attr, value|
  # value is an array of hashes
  # eg [{'name' => 'hi', 'url' => 'bye'}, ...]

  problems = ''
  if value
    value.each{|name_url| 
      problems << "Name #{name_url['name']} is missing its url. " \
        unless name_url['url']}
  else
    problems = 'Please supply at least one name and url'
  end
  record.errors.add(:urls, problems) unless problems.empty?
end

Added: you cannot use validations such as validates_length_ofsince the validation method does not understand the format of your serialized field.

The method validates_eachis good, as it allows you to write your own verification method. Then the method can add an error to the record, if necessary.

. :base record.errors, . .

+16

, - , , . , :

serialize :urls
validates_hash_keys :urls do
  validates :name, presence: true
  validates :url, presence: true
end

https://github.com/brycesenz/validates_serialized

+1

All Articles