Has_and_belongs_to_many with one-way "many"

Hi-

My model is such that I have Users who “own” 1 or more Contacts. My
schema is like this (abriged):

CREATE TABLE users (
id int primary key auto_increment,
first_namename varchar(40)
…more columns…
);

CREATE TABLE contacts(
id int primary key auto_increment,
…more columns…
);

CREATE TABLE user_contacts (
user_id int not null,
contact_id int null,
CONSTRAINT fk_uc_user FOREIGN KEY (user_id) REFERENCES user(id),
CONSTRAINT fk_uc_contact FOREIGN KEY (contact_id) REFERENCES
contacts(id),
);

Now, a user a can have multiple contacts, but from the other direction
a single contact is “owned” by only 1 user. Yes, I could put a
“user_id” column in the Contacts table and not have the linking table
there at all, but this seems like bad design.

Currently, my model is:

class Contact < ActiveRecord::Base
has_and_belongs_to_many :user, :join_table => “user_contacts”
end

and

class User < ActiveRecord::Base
has_and_belongs_to_many :contact, :join_table => “user_contacts”
end

and this works. However, when back tracking via a contact, its an array
for “user”:

c = Contact.find(4)
=> #<Contact:0xb7431200 @attributes={“created_on”=>“2006-09-12
22:08:24”, “dob”=>“2006-09-12”, “id”=>“4”, “first_name”=>“Foo”,
“last_name”=>“Bar”}>

c.user
=> [#<User:0xb794d164 @attributes={“created_on”=>“2006-09-11 23:58:28”,
“contact_id”=>“4”, “id”=>“1”, “user_id”=>“1”, “first_name”=>“Blah”,
“password”=>“xxxx”, “last_name”=>“Blubber”,
“email”=>“[email protected]”}>]

c.user[0].first_name
=> “Blah”

Notice the reference to the 0th array element. Now what I would like to
do is use my schema but have it enforce contact(many) to user(one)
relationships without loading an array of objects going from contact to
user. I think a “has_many :contact” in User is appropriate, but from
the Contact side I dont see which association works, “belong_to” doesnt
take any options that support going through a secondary join table.

What are my options?

Thanks in advance
/Cody

On 9/12/06, [email protected] [email protected] wrote:

My model is such that I have Users who “own” 1 or more Contacts. My
schema is like this (abriged):

Now, a user a can have multiple contacts, but from the other direction
a single contact is “owned” by only 1 user. Yes, I could put a
“user_id” column in the Contacts table and not have the linking table
there at all, but this seems like bad design.

Revisit this assumption and you’ll be pleased with the results.
Contact belongs_to :user
User has_many :contacts

jeremy