Ser*_*off 4 ruby-on-rails carrierwave
我试图确保图片模型的每个实例都附加了一个文件。
换句话说 - 表单中有两个字段:
:file
:remote_file_url
Run Code Online (Sandbox Code Playgroud)
我希望用户至少填写其中一项。
当我验证 :file 的存在并提交 remote_file_url 而不是 file 时 - 然后它会给出验证错误。
我现在找到的唯一方法是这样做:
class Picture < ActiveRecord::Base
validate :file_xor_remote_file_url
private
def file_xor_remote_file_url
if !(file.blank? ^ remote_file_url.blank?)
errors.add(:base, "Specify a file to upload, or file URL, not both")
end
end
end
Run Code Online (Sandbox Code Playgroud)
维基百科说你可以像这样验证你的上传:
mount_uploader :avatar, AvatarUploader
validates_presence_of :avatar
Run Code Online (Sandbox Code Playgroud)
它没有提到对远程 URL 的任何不同处理,但强调 Carrierwave 验证文件的存在而不仅仅是 URL 的存在。因此,给定的远程 URL 必须引用可以上传的有效文件。
您说“验证 :file 的存在”,但这也许就是重点。希望这可以帮助。
| 归档时间: |
|
| 查看次数: |
3518 次 |
| 最近记录: |