Pau*_*ulC 14 validation model ruby-on-rails ruby-on-rails-3
我正在编写一个Rails应用程序来管理我们网站顶部的一系列横幅; 每个应链接到编辑器提供的URL或从下拉列表中选择的特定产品.
为了与其他检查保持一致,我想在模型中进行某种验证,以确保在保存时提供了一个(但不是两个)字段(产品ID或URL).
有没有一种validates
方法来检查这个,还是我必须把这个检查放在控制器的某个地方呢?
apn*_*ing 18
这是模型中非常直接的验证:
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
Run Code Online (Sandbox Code Playgroud)
上面的类似答案,但这只是一个独家或if if语句是不需要的
validate :check_consistency
def check consistency
errors.add(:base, 'message') if product_id.blank? ^ url.blank?
end
Run Code Online (Sandbox Code Playgroud)