Paperclip - Validate File Type but not Presence
Asked Answered
I

4

6

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?

Incompatible answered 10/5, 2010 at 22:55 Comment(1)
I asked as similar question a while back #2257541 - I got it working with a proc. maybe it will help youFlycatcher
M
4

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
Meniscus answered 1/6, 2010 at 22:30 Comment(1)
I realised I had to do this after upgrading to Paperclip 2.3.2 from Paperclip 2.3.1.1Meniscus
K
1

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

Kissiah answered 20/3, 2012 at 20:3 Comment(0)
Z
0

chunk of my model:

  has_attached_file :logo, :styles => { :medium => ["300x300>", :png], :thumb => ["100x100>", :png] }
  validates_attachment_size :logo, :less_than => 2.megabytes
  validates_attachment_content_type :logo, :content_type => ['image/jpeg', 'image/png', 'image/gif']

and if I provide no image file, @obj.update_attributes(..) raises no error, but validates if I provide a file. Maybe you use older version of paperclip?

gem list | ack paperclip
paperclip (2.3.1.1)
Zebe answered 11/5, 2010 at 8:45 Comment(1)
I have version 2.3.2 and have the same problem :(Ybarra
B
0

First let me say that I am new to both ruby and rails. Secondly, I don't know if this can be applied to audio files but with images I just set up a default image so that one way or another there is a photo associated with each record.

has_attached_file :photo, styles: { small: "64x64", med: "100x100", large: "200x200" }, default_url: "/images/no-image-available.png"
Bullbat answered 21/6, 2017 at 1:8 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.