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 contact.email within an instance of my User class it will pick out the corresponding Contact for said User? Thanks for any help or pointers!
on 2007-01-15 17:06
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 && contact.email.nil? errors.add('email', 'Related contact must have email') end end Testing seems to work so I think it's right!