验证文件类型但不存在

验证文件类型但不存在

本文介绍了回形针 - 验证文件类型但不存在的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用回形针来处理我的文件上传,并且在一种情况下我不希望该文件是强制性的.但是,我确实想确保它存在时是特定的文件类型.

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.

我有这个:

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

当我没有声音文件时,它告诉我它不是有效的内容类型之一.我已经尝试将 '' 添加到 :content_type 数组,这也不起作用!

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!

我还尝试为 :if 属性创建一个 lambda 过程,但我无法让它在没有某种错误的情况下运行.

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

这里有什么遗漏吗?

推荐答案

我想您可以尝试条件验证",条件是文件是否存在?

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

这篇关于回形针 - 验证文件类型但不存在的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-20 05:35