Validating Uniqueness From Two Database Tables?

Well, I’m working on adding a new type of user (organization) to my
application, using a different database table than the standard User
table (in the end, I think it works out being easier to deal with than
creating another column in the original User table for account type).
However, I’m running into a user registration problem. I can register
both types of users fine, however, a screen name can be shared between
the different tables. For example, a user can register with the screen
name “foo”, and an organization can also register with the screen name
“foo”. Obviously, this creates login problems, so I’d like to try to
prevent this. Unless theres something I’m missing about
“validates_uniqueness_of”, that only works within one table. How can I
make my program check that the new screen name is unique to both tables?

Thanks for any help :slight_smile:

Hi Dan,

One way that springs to mind is:

class Organisation
validate :validates_uniqueness_of_screen_name

def validates_uniqueness_of_screen_name
in_org = Organisation.find(:first, :conditions => [‘screen_name
= ?’, screen_name])
in_user = in_org ? nil : User.find(:first, :conditions =>
[‘screen_name = ?’, screen_name])
errors.add(‘screen_name’, ‘is already taken’) if in_org or in_user
end
end

class User
validate :validates_uniqueness_of_screen_name

def validates_uniqueness_of_screen_name
in_org = Organisation.find(:first, :conditions => [‘screen_name
= ?’, screen_name])
in_user = in_org ? nil : User.find(:first, :conditions =>
[‘screen_name = ?’, screen_name])
errors.add(‘screen_name’, ‘is already taken’) if in_org or in_user
end
end

You could even add this in as a mixin if you feel inspired (that way
you don’t repeat yourself) :slight_smile:

Julian.

Learn Ruby on Rails! Check out the FREE VIDS (for a limited time)
VIDEO #4 parts a and b now available!
http://sensei.zenunit.com/

That works absolutely perfectly, thanks a bunch for your help Julian :slight_smile:

I think it was going to get messy no matter which way I did it. My
original User classes had a lot of associations that I didn’t want my
Organizations to have (for example, Users have an FAQ and a blog, which
Organizations shouldn’t have).

It gets a little messy using the same log in and register forms for
both, but I think in this case it works better to just use the two
separate tables (then again, I’m fairly new to Rails and all, so I could
very well be WAY off here).

I have a feeling that this could get very, very messy. IMO you’re
better off using single table inheritance in the User table.