Reputation: 3489
My users can choose between using an image url or uploading an image. One of both is required though.
How can I use validates_presence_of :url
with an "unless :image
is used". And vice versa.
I've managed to get this to work; But obviously this doesn't work. Because it will add the validation if the other one isn't present. I'm confused in to how to get ONLY ONE of both to be entered.
validates_presence_of :url, if: Proc.new { |a| a.pictogram.blank? }
validates_presence_of :pictogram, if: Proc.new { |a| a.url.blank? }
EDIT: I fixed it with
validate :addImageValidation
def addImageValidation
if !url.blank? && !image.blank?
errors.add(:image, "both not empty")
end
end
Upvotes: 1
Views: 183
Reputation: 2741
You can write your own validator:
validate :url_or_pictogram_but_not_both
def url_or_pictogram_but_not_both
unless url ^ pictogram
errors.add ...
end
end
Upvotes: 1