Ruby on Rails 3 and Paperclip gem: custom presence validation on an attachment (no use of 'validates_attachment_presence')
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 d开发者_C百科idn't expect it! You might have expected an instance of ActiveRecord::Base. The error occurred while evaluating nil.[]
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.
精彩评论