Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Paperclip - Validate File Type but not Presence

I am using paperclip to handle my file uploads, and in one situation I don't want the file to be mandatory. I do however want to make sure it is a specific file type when it is present.

I have this:

class TestModel < ActiveRecord::Base
    #stuff
    has_attached_file :sound #etc...
    validates_attachment_content_type :sound, :content_type => ['audio/mp3', 'application/x-mp3']
end

And when I have no sound file present, it tells me it is not one of the valid content types. I've tried adding '' to the :content_type array, which also doesn't work!

I also attempted creating a lambda procedure for the :if property, but I can't get it to run without some kind of error.

Anything missing here?

like image 785
Lowgain Avatar asked May 10 '10 22:05

Lowgain


2 Answers

I guess you could try a 'conditional validation' where the condition is if a file is present?

class TestModel < ActiveRecord::Base
  #stuff
  has_attached_file :sound #etc...
  validates_attachment_content_type :sound, :content_type => ['audio/mp3', 'application/x-mp3'], :if => :sound_attached?

  def sound_attached?
    self.sound.file?
  end
end
like image 80
lisimba.gilkes Avatar answered Nov 19 '22 13:11

lisimba.gilkes


This issue has been fixed in newer versions of paperclip (I think around 2.3.4 based on when the commit was made). See discussion at

https://github.com/thoughtbot/paperclip/issues/125

like image 26
Ryan Avatar answered Nov 19 '22 14:11

Ryan