Search code examples
ruby-on-railsrails-postgresql

What validations to use for an array data type


PostgreSQL adds other data types to the Active Record default.
See PostgreSQL documentation, List of available datatypes at Stackoverflow and Active Record and PostgreSQL at RailsGuides.
For the array data type it is necessary to add array: true in the migration. For instance:

create_table :books do |t|
  t.string 'title'
  t.string 'tags', array: true
  t.integer 'ratings', array: true
end

What kind of validations should be used in the Book model?
If integer was a non-array data type I would use:

validates :ratings, numericality: { only_integer: true, greater_than: 0 }

Would this validation be correct also in case ratings is an array data type?
I am interested in validating the array elements not the array itself.


Solution

  • AFAIK there is no built in validation for such case.

    You could write custom one:

    validate :valid_ratings
    
    private
    
    def valid_ratings
      if everything_is_ok
        true
      else
        errors.add(:ratings, 'ratings is invalid') if something_is_wrong
      end
    end