# Self refrencing many to one implementation

**URL:** <https://www.ruby-forum.com/t/self-refrencing-many-to-one-implementation/183831>\
**Category:** Rails\
**Created:** [February 21, 2010, 10:53am UTC](https://www.ruby-forum.com/t/self-refrencing-many-to-one-implementation/183831 "2010-02-21T10:53:24Z")\
**Posts on this page:** 2\
**Page:** 1

<div class="post-metadata">

**Author:** ![mac](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/cc9497/32.png) [@mac](https://www.ruby-forum.com/u/mac)\
**Post date:** [February 21, 2010, 10:53am UTC](https://www.ruby-forum.com/t/self-refrencing-many-to-one-implementation/183831/1 "2010-02-21T10:53:24Z")

</div>

hello,  
i have database for dynamic website in which i need to store  
information about each menu and its relationship with other menu.  
it is obvious that each menu can have several submenu but each submenu  
must belong to one and ony one menu.  
so database goes like this

Pk\_Content\_id=\>integer  
title =\>integer, it is name of menu  
Image\_path=\>string, path of image  
Content\_text=\> text contained on click of every menu or description  
fK\_parent\_content\_id =\> integer , THIS LINKS BACK TO pk\_content\_id ,as  
is a foreign key

what i want is to relate pk\_content\_id and fk\_parent\_content\_id (which  
are in same table)

how to accomplish such self refrencing many to one relation???

m extreme beginner in rails please be more descriptive.

just to mention pk- represents primary key so is unique while fk is  
foreign key and is not unique, combinaly forms one to many relation

thanks in advance

---

<div class="post-metadata">

**Author:** ![mac](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/m/cc9497/32.png) [@mac](https://www.ruby-forum.com/u/mac)\
**Post date:** [February 21, 2010, 11:09am UTC](https://www.ruby-forum.com/t/self-refrencing-many-to-one-implementation/183831/2 "2010-02-21T11:09:13Z")

</div>

On 21 February 2010 05:50, mac [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> Pk\_Content\_id=\>integer

The term you’re looking for is “self referential” - very handy when  
Authors have Readers, or Employees have Managers…

You’ll find lots of tutorials online, but essentially you set it up  
thus:

# Menu model

has\_many :children, :class\_name =\> “Menu”, :foreign\_key =\>  
“parent\_content\_id” # those ‘pk/fk’ prefixes are not really good from  
the Rails conventions  
belongs\_to :parent, , :class\_name =\> “Menu”

But you might find that one of the “nesting” algorithms suits your  
need better - seeing as it seems you might be constantly recurring  
down the menus, “awesome\_nested\_set” might be worth a look.

Hope this helps put you on track.
