1

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!

robbiep
  • 113
  • 1
  • 10

3 Answers3

1

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

Community
  • 1
  • 1
Btuman
  • 881
  • 2
  • 9
  • 37
1

I think Btuman's first answer would be considered canonical: The content_type key of content_type in validates_attachment can accept an array of valid content-types.

tilthouse
  • 425
  • 2
  • 10
  • There's always more than one way to do it. Maybe canonical isn't quite right. It's just the style I've personally always seen used, and is, I think better documented. Furthermore, I'd avoid the regular expression there, as I think it is needlessly complex. – tilthouse Jun 19 '13 at 18:16
  • Ah, true, I just wanted to include more then one way just in case, but I will edit the answer to make sure to add your point – Btuman Jun 19 '13 at 18:19
0

You can use :inclusion attribute for more see this http://guides.rubyonrails.org/active_record_validations_callbacks.html

sp1rs
  • 786
  • 8
  • 23