Mats Stijlaart
Mats Stijlaart

Reputation: 5098

Ruby relation between same model

I have a model in rails, lets say User, which i want to have a relation to another user.

User A, can be the boss of User B and User B can be the boss of User C and D.

This relation is a one-to-many. One user can stand above multiple users.

How would i do this.
My user model has currently an ID with the name boss_id, which will be nil if the user is in the top of the food chain.

My active record class looks like this:

class User < ActiveRecord::Base

  has_many :users #People beneath the user
  belongs_to :user
end

But now I want to use relation with a name. Lets say boss and followers.

How can I achieve this?

Upvotes: 1

Views: 113

Answers (2)

Manish Shrivastava
Manish Shrivastava

Reputation: 32070

It is called self join

Self Joins

In designing a data model, you will sometimes find a model that should have a relation to itself. For example, you may want to store all employees in a single database model, but be able to trace relationships such as between manager and subordinates. This situation can be modeled with self-joining associations:

Employee example:

class Employee < ActiveRecord::Base

  has_many :subordinates, :class_name => "Employee"
  belongs_to :manager, :class_name => "Employee", :foreign_key => "manager_id"

end

With this setup, you can retrieve @employee.subordinates and @employee.manager.

Upvotes: 1

Maur&#237;cio Linhares
Maur&#237;cio Linhares

Reputation: 40333

Here's how it would look like:

class User < ActiveRecord::Base

    belongs_to :boss, :class_name => 'User'
    has_many :followers, :class_name => 'User', :foreign_key => :boss_id

end

Upvotes: 6

Related Questions