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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With