Paperclip - Validate File Type but not Presence

ⅰ亾dé卋堺 提交于 2019-11-30 07:30:39

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

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

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)

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"
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!