Forum: Ruby on Rails Validating that a record in a related table exists

Announcement (2017-05-07): is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see and for other Rails- und Ruby-related community platforms.
E548b2000696761124fb7bf6a639f2a6?d=identicon&s=25 Draconid (Guest)
on 2007-01-15 17:06
Hi, I'm fairly new to Ruby and Rails.  I'm trying to get my models
validating and I've run into a problem.

I've got two models User and Contact.  User belongs_to contact and
contact has_one user.

A Contact can exist without a User, however a User cannot exist without
a corresponding Contact.

Also, the Contact model contains an email address.  This email address
can be null, but if there is a User corresponding with the Contact then
there must be an email address.

So basically, upon creating a user I need to check that (a) the
contact_id of the user exists in Contacts, and (b) that the email field
of the corresponding Contact is not blank.

Is there a special Rails way of doing this (particularly part a), or do
I need to create my own validation code (which I assume will be the case
for part b no matter what)?

Also, am I right in assuming that if I use within an
instance of my User class it will pick out the corresponding Contact for
said User?

Thanks for any help or pointers!
E548b2000696761124fb7bf6a639f2a6?d=identicon&s=25 Draconid (Guest)
on 2007-01-15 17:40
Okay, I think I've got it:

I've put in the User model "validates_presence_of :contact" to ensure
that the contact actually exists.

I've then added the following validates method:

  def validate
    if contact &&
      errors.add('email', 'Related contact must have email')

Testing seems to work so I think it's right!
This topic is locked and can not be replied to.