1

I have a model called RsvpRegistrations with

belongs_to :rsvp

I need to use values from the parent 'rsvp' object in my validations such as

validates_presence_of :phone if self.rsvp.phone 

(Rsvp.phone is boolean)

But this doesn't work. The error I get is undefined method `rsvp'. How can I access the parent object and its values?

Once I get it working, I have other similar validations to run, so I'm thinking I need to grab the parent 'rsvp' one time and then reference it in my other validations.

Thanks in advance.

Brett
  • 2,775
  • 4
  • 27
  • 32

2 Answers2

2
validates_presence_of :phone, :if => Proc.new { |obj| obj.rsvp.phone? }

More options here

Michaël Witrant
  • 7,525
  • 40
  • 44
  • This worked! Can't thank you enough. One further question though: I need to reference the parent object about 8 times in this model. Is there a better way to store the parent in some kind of instance variable and reference it in each of my validations, or is it fine just to repeat the code above with the various tweaks? – Brett Jul 13 '11 at 14:15
  • It's fine to repeat this code. The `rsvp` object will only be retrieved from the database the first time you access it. – Michaël Witrant Jul 13 '11 at 22:53
0

If you have multiple validations that all reference RSVP, it may be more efficient to create a custom validation method:

# app/models/rsvp_registration.rb
def RsvpRegistration
  def validate
    rsvp = self.rsvp
    errors.add(:rsvp, 'Phone is missing') unless rsvp.phone?
    errors.add(:rsvp, 'Other messages') if condition
  end
end
Ben Simpson
  • 4,009
  • 1
  • 18
  • 10