0

I want to do a file upload feature with Rails4.

Now I don't use database so I can't use the rails' validation to check if user selected a file on the browser.

But I want to do as this, a self created model:

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

I don't know how to write validation code in the model. I have tried:

validates :my_file, presence: true

But not worked. Is it also need to check validation in the controller?

s-cho-m
  • 967
  • 2
  • 13
  • 28
  • The code you have posted looks appropriate. Can you elaborate on how it doesn't work and post your controller code? Calling `valid?` on an instance of `MyFeature` (without a `my_file` attribute) should return `false` and have and have a presence error in `errors[:my_file]`. – ihaztehcodez Jul 15 '15 at 11:24

1 Answers1

1

Though it is not the best idea but you can try some thing like a custom 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

Please check the link similar to this question.

Community
  • 1
  • 1
Sabyasachi Ghosh
  • 2,765
  • 22
  • 33
  • Thank you. I have tried this in my controller: `MyFeature.new(my_file: params[:my_file]).valid?`, but it said: `undefined method `size' for nil:NilClass`. If user didn't choose a file from view, that param will be nil – s-cho-m Jul 16 '15 at 02:50
  • Valid will not work if params[:my_file] is blank or nil. Please try params[:my_file].blank? .so if params[:my_file] is nil then it will return true as the size. – Sabyasachi Ghosh Jul 16 '15 at 06:59