在上传之前对rails中的文件大小进行自定义验证

His*_*alv 10 validation activerecord ruby-on-rails-3

以我的形式,我有

<%= label_tag("file", "Attachment:") %><%= file_field_tag "uploadfile" %>
Run Code Online (Sandbox Code Playgroud)

在我的模型中,我想写这个

validate :validates_uploadfile

def validates_uploadfile(file)
    max_size = 2048
    errors.add(:uploadfile, "File size exceeds limitation") if file.size > max_size
end
Run Code Online (Sandbox Code Playgroud)

在我的控制器中我可以调用这样的东西

validates_upload_file(params[:uploadfile])
Run Code Online (Sandbox Code Playgroud)

有没有办法在上传之前验证文件上传(不是通过使用javascript或查看文件扩展名)
感谢您的帮助

UPD

validate :uploadfile_validation, :if => "uploadfile?"

def uploadfile_validation
    errors[:uploadfile] << "should be less than 1MB" if uploadfile.size > 1.megabytes
end
Run Code Online (Sandbox Code Playgroud)

Luc*_*cas 16

这是我的大小验证代码(我使用CarrierWave进行上传).

  validate :picture_size_validation, :if => "picture?"  

  def picture_size_validation
    errors[:picture] << "should be less than 1MB" if picture.size > 1.megabytes
  end
Run Code Online (Sandbox Code Playgroud)

干杯.


小智 9

您可以使用:

validates_size_of :picture, maximum: 1.megabytes, message: "should be less than 1MB"
Run Code Online (Sandbox Code Playgroud)