如何使用 rails 添加自定义文件上传验证模型?

How to add a custom file upload validation model with rails?

我想用 Rails4 做一个文件上传功能。

现在我不使用数据库,所以我不能使用 rails' 验证来检查用户是否在浏览器上选择了文件。

但我想这样做,一个自己创建的模型:

# app/models/my_feature.rb
class MyFeature
  include ActiveModel::Model
  attr_accessor :my_file
  # How to do next?
end

我不知道如何在模型中编写验证代码。我试过:

validates :my_file, presence: true

但是没用。是不是也需要在controller中检查validation?

虽然这不是最好的主意,但您可以尝试一些类似自定义验证的方法。

class MyFeature
  include ActiveModel::Model
  attr_accessor :my_file
  validate :image_validation, :if => "my_file?"  
  def image_validation
    errors[:my_file] << "size can not be zero" if my_file.size > 0
  end
end

请检查link similar 这个问题。