我试图确保 Picture 模型的每个实例都附加了一个文件。
换句话说 - 表单中有两个字段:
:file
:remote_file_url
我希望用户至少填写其中一项。
当我验证 :file 的存在,并提交 remote_file_url 而不是文件时,它会给出验证错误。
我现在找到的唯一方法是这样做:
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