Tags

  • AWS (7)
  • Apigee (3)
  • ArchLinux (5)
  • Array (6)
  • Backtracking (6)
  • BinarySearch (6)
  • C++ (19)
  • CI&CD (3)
  • Calculus (2)
  • DesignPattern (43)
  • DisasterRecovery (1)
  • Docker (8)
  • DynamicProgramming (20)
  • FileSystem (11)
  • Frontend (2)
  • FunctionalProgramming (1)
  • GCP (1)
  • Gentoo (6)
  • Git (15)
  • Golang (1)
  • Graph (10)
  • GraphQL (1)
  • Hardware (1)
  • Hash (1)
  • Kafka (1)
  • LinkedList (13)
  • Linux (27)
  • Lodash (2)
  • MacOS (3)
  • Makefile (1)
  • Map (5)
  • MathHistory (1)
  • MySQL (21)
  • Neovim (10)
  • Network (66)
  • Nginx (6)
  • Node.js (33)
  • OpenGL (6)
  • PriorityQueue (1)
  • ProgrammingLanguage (9)
  • Python (10)
  • RealAnalysis (20)
  • Recursion (3)
  • Redis (1)
  • RegularExpression (1)
  • Ruby (19)
  • SQLite (1)
  • Sentry (3)
  • Set (4)
  • Shell (3)
  • SoftwareEngineering (12)
  • Sorting (2)
  • Stack (4)
  • String (2)
  • SystemDesign (13)
  • Terraform (2)
  • Tree (24)
  • Trie (2)
  • TwoPointers (16)
  • TypeScript (3)
  • Ubuntu (4)
  • Home

    Polymorphic Associations

    Published Jun 02, 2022 [  Ruby  ]

    With polymorphic associations, a model can belong to more than one other model, on a single association. For example, you might have a picture model that belongs to either an employee model or a product model.

    class Picture < ApplicationRecord
      belongs_to :imageable, polymorphic: true
    end
    
    class Employee < ApplicationRecord
      has_many :pictures, as: :imageable
    end
    
    class Product < ApplicationRecord
      has_many :pictures, as: :imageable
    end
    

    You can think of a polymorphic belongs_to declaration as setting up an interface that any other model can use. From an instance of the Employee model, you can retrieve a collection of pictures: @employee.pictures.

    Similarly, you can retrieve @product.pictures.

    If you have an instance of the Picture model, you can get to its parent via @picture.imageable. To make this work, you need to declare both a foreign key column and a type column in the model that declares the polymorphic interface.

    class CreatePictures < ActiveRecord::Migration[7.0]
      def change
        create_table :pictures do |t|
          t.string  :name
          t.bigint  :imageable_id
          t.string  :imageable_type
          t.timestamps
        end
    
        add_index :pictures, [:imageable_type, :imageable_id]
      end
    end
    
    

    The migration can be simplified by using t.references form

    class CreatePictures < ActiveRecord::Migration[7.0]
      def change
        create_table :pictures do |t|
          t.string :name
          t.references :imageable, polymorphic: true
          t.timestamps
        end
      end
    end
    

    Reference