rails interview - polymorphic association
polymorphic association ::
polymorphic association is the association in which a model is belongs to many other models | the common example of the polymorphic association is the post model connect to group ,profile and image model.
the oop concept of polymorphism or the ability of an object to take many forms , is the foundation idea of these association in rails
if i want to use the one model with many other models then we will use the polymorphic association
self join ::
2.10 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:
class Employee < ApplicationRecord
has_many :subordinates, class_name: "Employee",
foreign_key: "manager_id"
belongs_to :manager, class_name: "Employee", optional: true
end
With this setup, you can retrieve @employee.subordinates and @employee.manager.
In your migrations/schema, you will add a references column to the model itself.
class CreateEmployees < ActiveRecord::Migration[6.0]
def change
create_table :employees do |t|
t.references :manager, foreign_key: { to_table: :employees }
t.timestamps
end
end
end
Comments
Post a Comment