Ruby on Rails 3 和 Paperclip gem:附件上的自定义存在验证(不使用“validates_attachment_presence”)
我正在使用 Ruby on Rails 3 的 'paperclip' gem,我想用这种方法处理自定义存在验证:“如果文件路径值(类似于“/Users”的字符串) /Desktop/image.gif
”或“C:/Users/Desktop/image.gif
”)未在“file_field”中输入会引发此字段的错误”。
我认为这样做有问题,因为 RoR 处理“file_field”的方式与其他字段不同。
注意:我不想使用“paperclip”中存在的“validates_attachment_presence”方法。
这是做我想做的事情的好方法吗?如果是这样,如何做到这一点?
我在控制器中尝试了代码:
if params[:user][:avatar].blank?
# I also used
# - 'nil?' instead of 'blank'
# - !params[:user][:avatar]
@user.errors.add( :avatar, "can not be blank" )
end
但是,如果我尝试使用空文件(零/空白路径值)提交表单,我会得到一个
无方法错误
当你没有预料到的时候,你得到了一个 nil 对象!
您可能期望有一个 ActiveRecord::Base 实例。
评估 nil 时发生错误。[]
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.[]
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
只是一个想法:您还可以使用 Javascript 不启用上传按钮,直到先在文本字段中输入内容。这避免了不必要的服务器往返。您可能想要验证您的 User.rb 模型是否使用 attr_accessible,该字段是否存在于该行中。
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.