Search code examples
ruby-on-railsrubyvalidationpaperclippaperclip-validation

Ruby validation - multiple permutations for a single hash


Say there is a hash field that can have two possible value permutations, "foo" and "bar". How can I validate the hash value is one of the two?

class ValidateMe
  validates :type => { :type => "foo" or :type => "bar" }
end

This results in an error. What is the proper way to handle this use case?


My actual case is using Paperclip to attach an image. I need to enforce the image is only .png or .jpg

class ValidateMe
  validates_attachment :image, 
                       presence => true, 
                       :content_type => { :content_type => "image/png" }
end

Help with either code block is greatly appreciated. Thanks!


Solution

  • The best way to do this would be to pass an array of types to :content_type

    class ValidateMe
      validates_attachment :image, 
                           presence => true, 
                           :content_type => { :content_type => ['image/png', 'image/jpeg'] }
    end
    

    (My answer is based on code in Paperclip - Validate File Type but not Presence)

    This can also be done using regular expressions. (Not as preferable)

    class ValidateMe
      validates_attachment :image, 
                           presence => true, 
                           :content_type => { :content_type => /^image\/(jpeg|png)$/ }
    end
    

    (source How can I restrict Paperclip to only accept images?)