Using two foreign keys to the same table


#1

i am working on a task manager with ruby on rails. it is my first major
project, so i’m still gettng my feet wet as i learn.

i’ve been trying to use the built in relationships to link my tables
together, but i’m not able to use the same naming conventions. for each
task, it has a field for the creator, and another field for the
assignee. both of these fields reference the users table. obviously i
can’t have two fields that say user_id in my tasks table, so how do i
get them to link right and specify a different field?

here is my current database schema:
Tasks
id int not null auto_increment,
task_name varchar(100) not null,
description text not null,
user_id int not null,
assignee int not null,
date_due date not null,
completed_at datetime not null,
constraint fk_task_user foreign key (user_id) references users(id),
constraint fk_task_assignee foreign key (assignee) references
users(id),

Users
id int not null auto_increment,
username varchar(20) not null,
password varchar(20) not null,
full_name varchar(100) not null,
email varchar(150) not null,
primary key (id)


#2

Josh K. wrote:

here is my current database schema:
users(id),

Users
id int not null auto_increment,
username varchar(20) not null,
password varchar(20) not null,
full_name varchar(100) not null,
email varchar(150) not null,
primary key (id)

(This is my first reply through the Gmane gateway, let’s hope it
works…)

You don’t have to name your foreign key user_id. Rails can indeed guess
the
correct relations when you do, but you can override. From the api docs:

belongs_to :author, :class_name => “Person”, :foreign_key => “author_id”

http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html#M000529

You could do something like

belongs_to :user, :foreign_key => “creator_id”
belongs_to :user, :foreign_key => “assignee_id”


#3

http://api.rubyonrails.com/classes/ActiveRecord/Associations/ClassMethods.html#M000529

You could do something like

belongs_to :user, :foreign_key => “creator_id”
belongs_to :user, :foreign_key => “assignee_id”

exactly what i was looking for. thanks.


#4

Jeremy E. wrote:

I doubt that will work. Try:

belongs_to :creator, :class_name=>‘User’, :foreign_key => “creator_id”
belongs_to :assignee, :class_name=>‘User’, :foreign_key => “assignee_id”

Which is also untested, but more likely to work.

Oh yeah, whoops. The association needs a name :slight_smile:


#5

On 4/6/06, Wiebe C. removed_email_address@domain.invalid wrote:

You could do something like

belongs_to :user, :foreign_key => “creator_id”
belongs_to :user, :foreign_key => “assignee_id”

I doubt that will work. Try:

belongs_to :creator, :class_name=>‘User’, :foreign_key => “creator_id”
belongs_to :assignee, :class_name=>‘User’, :foreign_key => “assignee_id”

Which is also untested, but more likely to work.