【问题标题】:Validate file size and number of images uploaded验证文件大小和上传的图像数量
【发布时间】:2014-09-24 08:35:59
【问题描述】:

我正在尝试验证使用carrierwave 上传的图像的大小以及用户上传的图像数量(最好将验证每个图像文件的大小)。

我正在通过以下方式使用nested_attributes

class Animal < ActiveRecord::Base
  has_many :animal_images, dependent: :destroy
  accepts_nested_attributes_for :animal_images, allow_destroy: :true, reject_if: proc { |attributes| attributes['image'].size > 2.megabytes }, limit: 3
end

因此,目前如果图像超过 2MB,如果会静默失败,并且如果用户尝试上传超过 3 张图像,那么我会收到 NestedAttributes::TooManyRecords 异常,从用户的角度来看,这看起来不太好。

我想做的是将这些验证包含在我当前的自定义验证方法中,以便我可以将错误添加到[:base]

def dog_form_validation
  if name.blank?
    errors[:base] << "Please provide your Dog's name"
  end
  if age.blank?
    errors[:base] << "Please provide your Dog's age"
  end
 // More validations here
end

如何访问 animal_image 数组,1) 检查它是否首先存在,然后 2) 检查它的大小?还是我想错了?

if animal_image[0].size > 2.megabytes
 errors[:base] << 'Please ensure file size is less than 2MB"
end

【问题讨论】:

  • 你是用paperclip还是carrierwave上传图片??
  • 用于图片上传的carrierwave,我会更新我的问题

标签: ruby validation activerecord ruby-on-rails-4


【解决方案1】:

你可能不得不使用

memsize_of(animale_image[0]) > 2.megabytes

number_to_human_size(File.size("#{animal_image[0]}"))

要使用number_to_human_size,请将include ActionView::Helpers::NumberHelper 添加到您的班级

【讨论】:

    猜你喜欢
    • 2011-06-24
    • 1970-01-01
    • 2022-01-12
    • 2011-08-07
    • 2011-04-12
    • 2012-04-12
    • 1970-01-01
    相关资源
    最近更新 更多