self referencing association in ruby on rails
In Ruby on Rails, a self-referencing association can be established by defining a model that references itself. To achieve this, you can use the belongs_to
and has_many
associations in the model class. Here's an example of how to create a self-referencing association in Ruby on Rails:
class Employee < ApplicationRecord
belongs_to :manager, class_name: "Employee", optional: true
has_many :subordinates, class_name: "Employee", foreign_key: "manager_id"
end
In this example, the Employee
model has a manager
association and a subordinates
association, both referencing the Employee
model itself. The belongs_to
association is used to establish the relationship between an employee and their manager, while the has_many
association is used to define the relationship between an employee and their subordinates. The class_name
option is used to specify the class name for the association, and the foreign_key
option is used to specify the foreign key for the association.
By setting up these associations, you can create a hierarchical structure within the Employee
model, allowing employees to be associated with other employees as their managers or subordinates. This can be useful for modeling organizational hierarchies or any other situations where entities have relationships with other entities of the same type.