Forum: Ruby on Rails Custom Validations

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
9618e8fca8d72bf01814276c53c2568c?d=identicon&s=25 Robert MannI (Guest)
on 2006-04-01 22:36
(Received via mailing list)
Does anyone how to create a validation that:

validates_presence_of :a  OR :b


I.e. :a OR :b must be present.

I thought this would probably be possible with some kind of validation
callback, e.g.:

def check_a_or_b_is_set
  return (a or b)
end



Any ideas?


Thanks,
Rob
C45aa3228424f6a35ebbfcd7a0e9d801?d=identicon&s=25 Ian White (Guest)
on 2006-04-01 23:22
(Received via mailing list)
How about something like:

validates_each :a do |record, attribute, value|
  if value.blank? and record.send(:b).blank?
    record.errors.add_to_base 'a or b required'
  end
end
Cb610750ee94ca103aef4b2dc7b1b768?d=identicon&s=25 Nick Stuart (Guest)
on 2006-04-02 04:06
(Received via mailing list)
Another way to do 'custom' validation is to simply supply a "validate"
method in your class. This gets called before you save/update. You can
simplify a bit what Ian has suggested.

#just place this in your model class
def validate
  errors.add_to_base "A or B are required" if a.blank? and b.blank?
end

Hope this helps!
-Nick
631d1677786f0725da6ccee46043686e?d=identicon&s=25 Jonathan Viney (Guest)
on 2006-04-02 04:12
(Received via mailing list)
You could do something like:

validates_presence_of :a, :if => Proc.new { |r| !r.b? }
validates_presence_of :b, :if => Proc.new { |r| !r.a? }

-Jonny.
9618e8fca8d72bf01814276c53c2568c?d=identicon&s=25 Robert MannI (Guest)
on 2006-04-02 10:50
(Received via mailing list)
Thanks alot for all three suggestions!

The "validate" callback was what I was looking for, as it allows me to
make
the validations as complex as I like.


Thanks!


Rob
This topic is locked and can not be replied to.