0

I am using the 'paperclip' gem for Ruby on Rails 3 and I would like to handle a custom presence validation with this approach: "if a file path value (a string like "/Users/Desktop/image.gif" or "C:/Users/Desktop/image.gif") is not entered in the 'file_field' throws an error for this field".

I think that I have a problem to do that because RoR handles differently 'file_field's than others fields.

Notice: I don't want use the 'validates_attachment_presence' method present in 'paperclip'.

Is it a good approach to do what I would like? If so, how to do that?


I tryed in my controller the code:

if params[:user][:avatar].blank?  
  # I also used 
  # - 'nil?' instead of 'blank'
  # - !params[:user][:avatar]
  @user.errors.add( :avatar, "can not be blank" )
end

but, if I try to submit the form with an empty file (a nil/blank path value), I get a

NoMethodError
You have a nil object when you didn't expect it!
You might have expected an instance of ActiveRecord::Base.
The error occurred while evaluating nil.[]

Nakilon
  • 34,866
  • 14
  • 107
  • 142
user502052
  • 14,803
  • 30
  • 109
  • 188

1 Answers1

1

Just an idea: you could also use Javascript to not enable the upload button until something is typed in the text field first. This avoids the need for unnecessary round trip to the server. You might want to validate that if your User.rb model is using attr_accessible, the field is present in that line.

jschorr
  • 3,034
  • 1
  • 17
  • 20
  • Can you make a real example of what you are sayng, especially on "You might want to validate that if your User.rb model is using attr_accessible, the field is present in that line"? – user502052 Jan 20 '11 at 00:27
  • I meant, in your User.rb model, if you're trying to pass in :avatar and are using attr_accessible to keep things safe, make sure that it looks like this: attr_accessor :avatar, :login, etc… Otherwise, that parameter won't be accepted. – jschorr Jan 20 '11 at 02:41