34

I want to self-referentiate a model in a RoR app but, I don't know exactly how. I want to save a linked list where the next node has the id of the previous one. how can I do this rails way? It is a one-to-one relation.

Yu Hao
  • 119,891
  • 44
  • 235
  • 294
JRafaelM
  • 861
  • 2
  • 10
  • 23
  • I think you start by searching StackOverflow for "[ruby-on-rails] self referential association": http://stackoverflow.com/search?q=%5Bruby-on-rails%5D%20self%20referential%20association - Duplicate? :-) – conny May 23 '11 at 12:49
  • 3
    actually I searched this, but they do not solve my problem. – JRafaelM May 23 '11 at 17:51

3 Answers3

81

The easiest way:

class MyModel < ActiveRecord::Base
  belongs_to :parent, :class_name => 'MyModel'
  has_many :children, :class_name => 'MyModel', :foreign_key => 'parent_id'
end
Hck
  • 9,087
  • 2
  • 30
  • 25
29

rails 5

add column xxx_id in users table:

in migration file:

add_reference :users, :xxx, index: true

and add code in User model

has_many :users, class_name: 'User', foreign_key: 'xxx_id'
belongs_to :manager, class_name: 'User', foreign_key: 'xxx_id'

If you don't have a manager for every user, you need to add optional: true.

'foreign_key' is not necessary. By default this is guessed to be the name of this class in lower-case and “_id” suffixed.

if foreign_key is user_id, user don't have manager necessary. the result is:

has_many :users, class_name: 'User'
belongs_to :manager, class_name: 'User', optional: true

They are called self-joins

Kaka Ruto
  • 4,581
  • 1
  • 31
  • 39
YaEvan
  • 660
  • 9
  • 12
3

I've spent some time trying to make it work using Rails 3.2.14

The documentation's suggestion for self-joining associations hasn't worked for belongs_to associations. Adding a foreign key fixed the issue.

Class User < ActiveRecord::Base
  has_many :invitees, class_name: 'User', foreign_key: :invited_by
  belongs_to :host, class_name: 'User', foreign_key: :invited_by
end
Vadym Tyemirov
  • 8,288
  • 4
  • 42
  • 38