Single Table Inheritance and validation

Hello guys,

I’ve got a User table, which is inherited by AdminUser and Supplier.
In my User model, I have a validates_uniqueness_of :email however I
am still able to store records with duplicate email addresses.

Does anyone have any suggestions why this might be occurring?

Thanks,

Alastair


Alastair M.
Standards compliant web development with Ruby On Rails, PHP and ASP
www.kozmo.co.uk
07738 399038

Alastair M. wrote:

I’ve got a User table, which is inherited by AdminUser and Supplier.
In my User model, I have a validates_uniqueness_of :email however I
am still able to store records with duplicate email addresses.

Where did you define your validation rule? (It should be inside the
parent model User if you want it to affect all children.)

Also, do your AdminUser and Supplier models extend User or ActiveRecord?
They’ll need to extend User if the rule is to be applied to them.

Maybe try putting the validation on the AdminUser and Supplier models
directly. Let me know if that works. I seem to recall having to do that
in
my app.

Brian H. wrote:

Maybe try putting the validation on the AdminUser and Supplier models
directly. Let me know if that works. I seem to recall having to do that
in my app.

You shouldn’t have to. And doing so would indicate you’re not inheriting
from the User model.

Example, bad:

class UserAdmin < ActiveRecord::Base
end

Example, good:

class UserAdmin < User
end

The Rails generator does not do this automatically for you, so you must.

On 29 Aug 2006, at 18:57, Daniel W. wrote:

ActiveRecord?
They’ll need to extend User if the rule is to be applied to them.

My validation rule was in the User model and my Admin/Supplier models
extend User. In the end, I found a method someone had written who was
having a similar problem to me.

http://work.alexyoung.org/archives/99/single-table-inheritance-and-
validates_as_unique

This seems to have fixed the problem.

Cheers!

Alastair


Alastair M.
Standards compliant web development with Ruby On Rails, PHP and ASP
www.kozmo.co.uk
07738 399038

Alastair M. wrote:

http://work.alexyoung.org/archives/99/single-table-inheritance-and-
validates_as_unique

That’s pretty cool. Nice find and thanks for sharing. =)

Hi Alastair,

Did you ever solve this problem? I have this EXACT issue myself. I
ASSumed that the validates_unique was working because I’ve seen it
working but didn’t think to check for trying to have the same email
for a different subtype. I immediately put a unique index on the
email column and am looking for the right rails validation to set for
this to work properly at the application layer. I don’t care what
folks say about being able to through out FK constraints, this little
episode is enough for me now to make sure they are everywhere I need
to ensure integrity.

Best,

-Michael
http://javathehutt.blogspot.com