Search code examples
ruby-on-railsactiverecordpolymorphic-associations

Polymorphic Associations - rails


I have some trouble understanding polymorphic associations in rails. How is

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

different from

class Picture < ApplicationRecord
  belongs_to :employee
  belongs_to :product
end

class Employee < ApplicationRecord
  has_many :pictures
end

class Product < ApplicationRecord
  has_many :pictures
end

Solution

  • In the second case you will need to add two foreign keys i.e employee_id and product_id in pictures table.

    Where as in first case t.references :imageable, polymorphic: true in your pictures migration will add two fields in pictures table i.e

    t.integer :imageable_id
    t.string  :imageable_type
    

    imagable_type field will be the name of class with whom you are associating this model to and imagable_id will hold the id of that record.

    e.g,

    Typical rows of picture table will look like

    id | name | imagable_id | imagable_type |
    
    1  | pic1 | 1           | Employee      |
    2  | pic2 | 3           | Product       |
    

    So here, Picture of first row will belong to Employee model holding the picture of Employee with id 1. Second row will belong to Product model holding the picture of product with id 3

    Advantages of first Approach is you can associate picture model any other model in future without having to add foreign key to it.

    Just add the line

    has_many :pictures, as: :imageable
    

    and association will be set.