# How to Model a table with two foreign keys of the same table

**URL:** <https://www.ruby-forum.com/t/how-to-model-a-table-with-two-foreign-keys-of-the-same-table/83864>\
**Category:** Rails\
**Created:** [January 30, 2007, 10:50am UTC](https://www.ruby-forum.com/t/how-to-model-a-table-with-two-foreign-keys-of-the-same-table/83864 "2007-01-30T10:50:33Z")\
**Posts on this page:** 3\
**Page:** 1

<div class="post-metadata">

**Author:** ![james\_027](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/4af34b/32.png) [@james\_027](https://www.ruby-forum.com/u/james_027)\
**Post date:** [January 30, 2007, 10:50am UTC](https://www.ruby-forum.com/t/how-to-model-a-table-with-two-foreign-keys-of-the-same-table/83864/1 "2007-01-30T10:50:33Z")

</div>

Hi the following table

JobOrder: fields(id, date\_filed, date\_needed, request\_by, process\_by,  
details, date\_finished)  
Employee(id, name)

the request\_by and the process\_by field are the foreign key of the  
table emplyee.

How will the model look like?

class Joborder \< ActiveRecord::Base  
belongs\_to :employee, :class\_name =\> “Employee”, :foreign\_key = \>  
“request\_by”  
belongs\_to :employee, :class\_name =\> “Employee”, :foreign\_key =\>  
“process\_by”  
end

Is the model above the correct way?

Thanks

---

<div class="post-metadata">

**Author:** ![james\_027](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/4af34b/32.png) [@james\_027](https://www.ruby-forum.com/u/james_027)\
**Post date:** [January 30, 2007, 10:53am UTC](https://www.ruby-forum.com/t/how-to-model-a-table-with-two-foreign-keys-of-the-same-table/83864/2 "2007-01-30T10:53:23Z")

</div>

i think they should have different names  
…  
belongs\_to :employee1, …  
belongs\_to :employee2, …  
…  
the mapping is done through the class\_name and the foreign\_key

---

<div class="post-metadata">

**Author:** ![james\_027](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/j/4af34b/32.png) [@james\_027](https://www.ruby-forum.com/u/james_027)\
**Post date:** [January 30, 2007, 11:03am UTC](https://www.ruby-forum.com/t/how-to-model-a-table-with-two-foreign-keys-of-the-same-table/83864/3 "2007-01-30T11:03:07Z")

</div>

P. Pantouffe wrote:

> i think they should have different names  
> …  
> belongs\_to :employee1, …  
> belongs\_to :employee2, …  
> …  
> the mapping is done through the class\_name and the foreign\_key

Only thing I’d add is more sensible variable names (which is implied, I  
think).

class Joborder \< ActiveRecord::Base  
belongs\_to :requestor, :class\_name =\> “Employee”, :foreign\_key = \>  
“request\_by”  
belongs\_to :processor, :class\_name =\> “Employee”, :foreign\_key =\>  
“process\_by”  
end

This will let you do @job\_order.processor… or @job\_order.requestor…

A.
