Rails 3 - validating one of two fields has been completed
I'm writing a Rails app to manage a series of banners along the top of our website; each one should link either to a URL provided by the editor, or a specific product selected from a drop-down list.
I'd like to put some kind of validation in the model, for consistency with other checks, that makes sure one (but not both) of the fields (product ID or URL) has been provided when saving.
Is there a validates
-type way to check this, or will I have to开发者_如何转开发 put this check somewhere in the controller instead?
It's a pretty straight validation in the model:
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
Similar answer to above but this is just an exclusive or and if else statements aren't needed
validate :check_consistency
def check consistency
errors.add(:base, 'message') if product_id.blank? ^ url.blank?
end
精彩评论