我正在编写一个 Rails 应用程序来管理我们网站顶部的一系列横幅;每个人都应该链接到编辑器提供的 URL,或从下拉列表中选择的特定产品。
我想在模型中进行某种验证,以与其他检查保持一致,以确保在保存时提供了一个(但不是两个)字段(产品 ID 或 URL)。
有没有validates
-type 方法来检查这个,还是我必须把这个检查放在 Controller 的某个地方?
最佳答案
这是模型中非常直接的验证:
validate :check_consistency
def check_consistency
if product_id.blank? and url.blank?
#one at least must be filled in, add a custom error message
return false
elsif !product_id.blank? and !url.blank?
#both can't be filled in, add custom error message
return false
else
return true
end
end
关于ruby-on-rails - Rails 3 - 验证两个字段之一已完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6694854/