Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 911
PaulC Avatar asked Jul 14 '11 14:07

PaulC


1 Answers

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
like image 134
apneadiving Avatar answered Sep 26 '22 03:09

apneadiving