Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails - Skip rails validation for subclass

I have a User class, and a Contact where Contact is a subclass of User. Both classes are stored in a users table.

My Contacts may or may not have an email address, while an email address is required for my Users (I have validates_presence_of :email in my User model definition).

My reasoning is that Contacts are entered by users and may later become Users when they claim their profile.

  • First of all, is it ok to define my users and contacts the way I did it?
  • Second, how do I skip the validate_presence_of email validation in my contacts model?

(I'm on rails 2.3.8)

Thanks!

UPDATE:

  • It seems Single Table Inheritance is designed to do exactly what I needed

  • the right way to skip validation for the presence of email for my Contact table is as follow:

validates_presence_of :email, :unless => Proc.new {|user| user.type == "Contact"}

like image 212
alex Avatar asked Apr 24 '11 21:04

alex


1 Answers

It sounds like you should abstract out User and Contacts into two tables instead of trying to consolidate them into one. Although contacts can become users, that doesn't mean that they will (I think?).

This would also solve your validate_presence_of :email question, as the contact table/model wouldn't even have the field. It would also alleviate potential performance concerns later on, I believe. You wouldn't want to have a ton of contacts to sort through to find a registered user.

If you're dead-set on doing it in one table though, I believe you can do something like the following:

validates_presence_of :email, :unless => Proc.new {|user| user.type == "Contact"}

This is assuming that you have a user_type column, but you could replace that depending on how you're determining whether a User is a Contact.

Update:

This is how you'd correctly validate the models: Remove the validates_presence_of from the model and place it inside of this block:

with_options :unless => :user_type == "contact" do |user|
   user.validates_presence_of :email
end
like image 83
Chuck Callebs Avatar answered Oct 25 '22 15:10

Chuck Callebs